4

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.

6

(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).

  • You answered my question perfectly. And sorry, I wrote that last night when I was half awake. Should have waited today. Thank you though. – user0000001 Jun 18 '16 at 15:37
  • 3
    You still should improve your question, at least for future readers. – Basile Starynkevitch Jun 18 '16 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.