Implement a dual-Buffer Queue and a dual-Buffer Queue
In the producer-consumer mode, we often use a queue, which has mutex and competitive operations when multiple threads share access, meaning that each access is locked. How can we better reduce the number of lock competitions? The dual-Buffer Queue to be introduced today is a good choice.
The dual-Buffer Queue is directed at the synchronization/mutex overhead. We know that when multiple threads concurrently access the same resource, we need to pay special attention to the thread synchronization problem. A little careless. Oh, the program results are incorrect.
Principle
Direct:
Lock
In the dual-Buffer Queue, the lock not only protects data security, but also undertakes the task of thread scheduling.
- Both the two-queue switching locations and the task queuing operation must be performed on the current queue. Therefore, they are mutually exclusive operations.
- The consumption operation is placed in a separate thread. When no task comes in, you need to set the thread to the waiting state.
Two semaphores are used to schedule operations in the queue and exchange queue. At the same time, we also need a semaphore to block the entire consumption thread when no task is in the queue.
We mainly use AutoResetEvent and ManualResetEvent. You can refer to the articles in the garden for specific usage:
Http://www.cnblogs.com/springyangwc/archive/2011/10/12/2208991.html
Implementation
I will use a simple example to demonstrate the entire process.
In the production line, enter some strings in the queue. Use the consumption thread to print these strings and the number of the queue in which they are located:
Let's take a look at the running effect:
As you can see, in the consumption thread, the queue exchange is used.
Next, we will implement an encapsulation of Dual-buffer queues.