Search code examples
c++cmultithreadingvisual-c++critical-section

How to lock Queue variable address instead of using Critical Section?


I have 2 threads and global Queue, one thread (t1) push the data and another one(t2) pops the data, I wanted to sync this operation without using function where we can use that queue with critical section using windows API.

The Queue is global, and I wanted to know how to sync, is it done by locking address of Queue?

Is it possible to use Boost Library for the above problem?


Solution

  • One approach is to have two queues instead of one:

    • The producer thread pushes items to queue A.
    • When the consumer thread wants to pop items, queue A is swapped with empty queue B.
    • The producer thread continues pushing items to the fresh queue A.
    • The consumer, uninterrupted, consumes items off queue B and empties it.
    • Queue A is swapped with queue B etc.

    The only locking/blocking/synchronization happens when the queues are being swapped, which should be a fast operation since it's really a matter of swapping two pointers.