I am trying to create a thread that will sit and wait to detect new objects in a vector (the queue). Using a loop will crush the resources on the given machine, so I am trying to figure out how I can create a blocking thread that waits for a notification from the main thread.The application will essentially wait for new objects in the vector and do some heavy IO operations - reading large files, compressing them, and writing back to disk.
How to signal a loop to continue the execution instead of using sleep
c++;multithreading
(I am not sure to understand what you want; I'm trying to guess; asynchronous IO could mean aio(7) but then you won't speak of threads to do them; however I am supposing you are on Linux - adapt my answer to other OSes)You might consider using condition variables using std::condition_variable with std::mutex (probably some other thread would signal the condition variable, e.g. when adding to the queue). If you are not familiar with the concepts, see this pthread tutorial (then adapt the ideas to C++11 threads).On POSIX systems such as Linux, you can check that a set of file descriptors is readable or writable using poll(2), etc... in some event loop; see also this; and you can carefully use SIGIO (see signal(7) and signal-safety(7) first ...; beware that you can only call async-signal-safe functions from signal handlers - which excludes most of C++ or C standard libraries; in practice, you can safely set some volatile sigatomic_t flags inside it, and test these flags elsewhere, e.g. in the event loop). And you could also setup some pipe(7) to self at program initialization time, and write(2) to it from a signal handler (BTW, this trick is recommended by Qt, in Calling Qt Functions From Unix Signal Handlers), or within a mutexed critical section.PS. Do not confuse Unix signals with signaling or broadcasting a condition variable (which you cannot reliably do from inside a Unix signal(7) handler). 