need a good solution for synchronized read write

2019-08-25 20:07发布

问题:

I have a thread(WRITER) that continuously populates a buffer(a vector in my case) as the incoming data arrive. And i have another thread(READER) that periodically checks the buffer for incoming data and clears the buffer after processing data is done. Once I saw an implementation that suggested to have two buffers (A and B) instead. the WRITER writes into buffer A, and when it is the time for reading the data, the READER takes over buffer A and WRITER starts reading into B...and this flipping continues.

I googled for a reference or sample code but couldn't find any. Can you please suggest me a reference? Also, is this the best and simplest approach?

thank you

回答1:

The simplest solution is using a syncronized queue with the help of the Boost libraries.

There is an article about this on CodeProject here, and countless examples on Google.



回答2:

You can find many samples and tips for implementing a synchronized queue:

Implementing a Thread-Safe Queue using Condition Variables

C++11 Concurrency Tutorial – Part 3: Advanced locking and condition variables