Implement a dual-Buffer Queue and a dual-Buffer Queue

Source: Internet
Author: User

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.

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.