Producer-consumer problem (Producer: 1, Consumer: 2, Buffer: 4)

Change the consumers to 2 and the buffer pool to a large buffer pool with 4 buffers.

    How to think about this problem? First of all, according to the two points analyzed above, it can be known that the change of producers and consumers from one to multiple has little effect. The only thing to note is that the buffer pool has become larger. Review the classic thread synchronization signal in the eighth chapter of "Seckill Multithreading " According to the semaphore in Semaphore , it is not difficult to use two semaphores to solve the situation where there are multiple buffers in the buffer pool - use one semaphore A to record the number of empty buffers, and another semaphore Quantity B records the number of non-empty buffers, then the producer waits for semaphore A , and the consumer waits for semaphore B. Therefore, the complex producer-consumer problem can be implemented by imitating the above code. The sample code is as follows:



So far, the producer-consumer problem has been satisfactorily resolved. Here is a summary :

1. The first thing to consider is the mutual exclusion between producers and consumers when they operate on the buffer.

2. No matter how many producers and consumers there are, how many buffers there are in the buffer pool. There are only two synchronization processes - the producer waits for an empty buffer before placing the product, and the consumer waits for a non-empty buffer to fetch the product.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324836144&siteId=291194637