Write a producer-consumer model in C language

Write a producer-consumer model in C language

The producer and consumer problem is a classic synchronization problem in the operating system, which is mainly used to solve the access conflict of the shared buffer. In this problem, there are two classes of threads: producers and consumers, which share a fixed-size buffer.

The task of the producer is to put elements into the buffer, and the task of the consumer is to get elements out of the buffer. In order to prevent multiple threads from reading and writing the same memory address at the same time, operations between them need to be synchronized. This article will introduce how to use C language to implement the producer consumer model.

First, let's define a buffer structure, which contains the size of the buffer, the current number of elements, and a pointer to the buffer:

#define BUFFER_SIZE 10

typedef struct {
    int buffer[BUFFER_SIZE];
    int in;
    int out;
    int count;
} buffer_t;

Here, we define the maximum capacity of the buffer as 10, inindicating the index of the next write position, outindicating the index of the next read position, and countindicating the current number of elements in the buffer.

Next, we define two functions for the execution of producer and consumer threads respectively:

void *producer(void *arg)
{
    buffer_t *buffer = (buffer_t *)arg;

    for (int i = 0; i < 100; i++) {
        // 等待缓冲区中有空闲位置
        while (buffer->count == BUFFER_SIZE);

        // 生产元素并写入缓冲区
        buffer->buffer[buffer->in] = i;
        buffer->in = (b

おすすめ

転載: blog.csdn.net/qq_39605374/article/details/132293557