3.12, producer consumer model

1. Introduction to producer consumer model

  • The producer-consumer model is a multi-threaded design pattern for solving synchronization and collaboration problems between producers and consumers.

  • In the producer-consumer model, producers and consumers exchange information by sharing a buffer. Producers put data into the buffer, and consumers retrieve data from the buffer. But because the buffer is limited , when the producer puts data into the buffer, if the buffer is full, then the producer must wait for the consumer to take some data from the buffer to make room for new data. Similarly, when the consumer fetches data from the buffer, if the buffer is empty, the consumer must wait for the producer to put some data into the buffer in order to fetch it.

  • In the producer consumer model, inter-thread communication is very important. In order to ensure the safety and correctness of data, it is necessary to use synchronization and mutual exclusion mechanism to control the access to the shared buffer. Generally, semaphores or mutexes are used to realize thread synchronization and mutual exclusion.

insert image description here

2. A producer-consumer model that does not implement thread synchronization

/*
    实现生产者消费者模型
        - 不考虑容量大小会满
        - 不考虑消费者会消费完产品
        因此这是一个错误的生产者消费者模型
*/

#include <iostream>
#include <pthread.h>
#include <cstring>
#include <unistd.h>

using namespace std;

struct Node
{
    
    
    int num;
    struct Node * next;
};

struct Node * head = nullptr;

void * producer(void * arg)
{
    
    
    while (1)
    {
    
    
        struct Node * newNode = (struct Node *) malloc(sizeof (struct Node));
        newNode->num = rand() % 1000;
        newNode->next = head;
        head = newNode;
        printf("add: newNode->num: %d, tid: %ld\n", newNode->num, pthread_self());
        usleep(100);
    }
    pthread_exit(NULL);
}

void * customer(void * arg)
{
    
    
    while (1)
    {
    
    
        struct Node * Num = head;
        head = head->next;
        printf("del: Num->num: %d, tid: %ld\n", Num->num, pthread_self());
        free(Num);
        usleep(100);
    }
    pthread_exit(NULL);
}

int main()
{
    
    
    pthread_t ptid[5], ctid[5];

    for (int i = 0; i < 5; i ++ )
    {
    
    
        pthread_create(&ptid[i], NULL, producer, NULL);
        pthread_create(&ctid[i], NULL, customer, NULL);
    }

    for (int i = 0; i < 5; i ++ )
    {
    
    
        pthread_detach(ptid[i]);
        pthread_detach(ctid[i]);
    }

    while (1)
    {
    
    
        sleep(10);
    }

    pthread_exit(NULL);

    return 0;
}

Guess you like

Origin blog.csdn.net/z2812470857/article/details/130104298