Realization of advanced first out shared memory segment based on producer-consumer model
Producer consumer issues: This problem describes the two processes that share fixed-size buffers-so-called "producers" and "consumers"-that can occur when they actually run. The primary role of the producer is to generate a certain amount of data into the buffer, and then repeat the process. Consumers, meanwhile, are consuming the data in the buffer zone. The key to this problem is to ensure that producers do not add data when the buffer is full, nor do consumers consume data when the buffer is hollow.
We can use semaphores to solve the problem of producer consumers, as shown below:
Defines 3 semaphores, sem_full and Sem_empty are used to synchronize between the producer process and the consumer process, that is, the buffer is empty to produce, and the buffer is not empty to consume. Because sharing the same block of buffers, in the production of a product process can not produce/consumer products, in the process of consuming a product can not produce/consumer products, so then use a Sem_mutex semaphore to constrain behavior, that is, mutual exclusion between processes.
The following is based on the producer consumer model to implement an advanced first-out shared memory segment:
As shown in the figure above, the definition of two structures, Shmhead is the head of the shared memory segment, save block size, block number, read and write index. Shmfifo saves the pointer to the shared memory head, the starting address of the payload, the shmid of the shared memory segment created, and 3 semaphores.