c++ - why do I need std::condition_variable? -


i found std::condition_variable difficult use due spurious wakeups. need set flags such as:

atomic<bool> is_ready; 

i set is_ready true before call notify (notify_one() or notify_all()), , wait:

some_condition_variable.wait(some_unique_lock, [&is_ready]{     return bool(is_ready); }); 

is there reason shouldn't this: (edit: ok, bad idea.)

while(!is_ready) {     this_thread::wait_for(some_duration); //edit: changed this_thread::yield(); } 

and if condition_variable had chosen waiting duration (i don't know whether true or not), prefer choose myself.

you can code either way:

  1. using atomics , polling loop.
  2. using condition_variable.

i've coded both ways below. on system can monitor in real time how cpu given process using.

first polling loop:

#include <atomic> #include <chrono> #include <iostream> #include <thread>  std::atomic<bool> is_ready(false);  void test() {     std::this_thread::sleep_for(std::chrono::seconds(30));     is_ready.store(true); }  int main() {     std::thread t(test);     while (!is_ready.load())         std::this_thread::yield();     t.join(); } 

for me takes 30 seconds execute, , while executing process takes 99.6% of cpu.

alternatively condition_variable:

#include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <thread>  bool is_ready(false); std::mutex m; std::condition_variable cv;  void test() {     std::this_thread::sleep_for(std::chrono::seconds(30));     std::unique_lock<std::mutex> lk(m);     is_ready = true;     cv.notify_one(); }  int main() {     std::thread t(test);     std::unique_lock<std::mutex> lk(m);     while (!is_ready)     {         cv.wait(lk);         if (!is_ready)             std::cout << "spurious wake up!\n";     }     t.join(); } 

this has exact same behavior except during 30 second execution, process taking 0.0% cpu. if you're writing app might execute on battery powered device, latter infinitely easier on battery.

now admittedly, if had poor implementation of std::condition_variable, have same inefficiency polling loop. in practice such vendor ought go out of business quickly.

update

for grins augmented condition_variable wait loop spurious wakeup detector. ran again, , did not print out anything. not 1 spurious wakeup. of course not guaranteed. demonstrate quality implementation can achieve.


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 -