c++ - Can single condition variable be used for bidirectional synchronization? -


is possible use single condition variable bidirectional synchronization (i.e. 2 different conditions waited @ different times on same condition variable)? i'm sure no more 1 thread wait on condition variable @ time. example code below illustrates i'm thinking about:

#include <condition_variable> #include <thread> #include <mutex> #include <iostream>  std::condition_variable condvar; std::mutex mutex; int i;  void even() {     while (i < 10000) {         std::unique_lock<std::mutex> lock(mutex);         if (i % 2 != 0) {             condvar.notify_one();             condvar.wait(lock, [&](){ return % 2 == 0; });         }         i++;         std::cout << << std::endl;     }     condvar.notify_one(); }  void odd() {     while (i < 10001) {         std::unique_lock<std::mutex> lock(mutex);         if (i % 2 != 1) {             condvar.notify_one();             condvar.wait(lock, [&](){ return % 2 == 1; });         }         i++;         std::cout << << std::endl;     } }  int main() {     = 0;     std::thread a(even);     std::thread b(odd);     a.join();     b.join(); } 

yes, it's safe. however, wouldn't habit of calling notify_one when want notify all threads waiting condition, if "know" 1 thread waiting.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -