Another way to check std::queue event?

c++, events, multithreading, queue, std

Solution

`std::queue` has absolutely nothing to do with threads. At all. Its `.empty()` member is not thread-safe (only reentrant)! The same applies to all it's other members. So multiple threads can use different queues whatever they like, but only one thread at a time can do anything at all with each instance.

C++11 or C++03 matters a lot. Because C++11 defines thread synchronization primitives, while C++03 does not and you have to use OS API.

In C++11 you would be interested in `std::condition_variable`.

In C++03 you would be interested in either Boost.Thread (mostly compatible with C++11) Events or Semaphores.

In either case the `std::queue::push()` and `std::queue::pop()` themselves must be protected by a mutual exclusion. The `std::condition_variable` even forces you to use one (`std::mutex`), in Windows API you'd use Critical Section.

On Windows, the C++11 classes are only available in Visual Studio 2012 and Windows 8. With older compiler use Boost (the advantage is that it will be portable) or native API.

Problem

Well, I'm trying to work on some kind of queue. I have an IO thread that it's dedicated for popping data out of the std::queue but the problem is that I'm using a Sleep() in order to prevent 100% cpu constant checking. And of course other threads which will add items to the std::queue. How could I make an event so that the thread is dormant and only initiates when the std::queue is NOT empty? IO Thread ``` Sleep(100); while (!myqueue.empty()) { //process data FIFO myqueue.pop(); //pop out and continue } ``` Much appreciated, thank you! Oh and this is for c++11 or c++03 it doesn't matter - on Windows.

Original source