Search code examples
c++multithreadingsynchronizationpthreadswakeup

C++ pthread synchronization and multiple wake up for thread


a question about C++ thread synchronization. We suppose that have 2 pthreads: Thread1 and Thread2.

  • Thread1 is engaged in its task and, in some cases, he must notify the update of the state to the Thread2.

  • Thread2 is engaged in its work of extracting data from a synchronized queue. So, the Thread2 can sleep if the queue is empty.

How can I wake up the Thread2 on two conditions:

  • New message notification in the queue;

    or

  • status change of the Thread1

practical code-examples are welcome


Solution

  • For simplicity's sake, make Thread1 insert the status change notification as a task in the queue where it can be consumed by Thread2. If the notification has higher priority than regular work tasks, allow Thread1 to insert it in the queue ahead of other tasks, making it the next one to be consumed.