Linux Network Programming System V Semaphore (iii)

Source: Internet
Author: User
Tags semaphore

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.