Monday 18 June 2018

Mutex, condition varaible

// condition_variable example
#include            // std::cout
#include              // std::thread
#include               // std::mutex, std::unique_lock
#include  // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
  std::unique_lock lck(mtx);
// equivalent to mtx.lock();
while (!ready) cv.wait(lck);//waiting for notification // ... std::cout << "thread " << id << '\n'; }//
// <---- brace="" equivalent="" however="" leave="" mtx.unlock="" span="" this="" to="" you="">
void go() { std::unique_lock lck(mtx); ready = true; cv.notify_all();//notify to all threads who is waiting } int main () { std::thread threads[10]; // spawn 10 threads: for (int i=0; i<10 i="" kbd="" print_id="" std::cout="" std::thread="" style="color: #600030; font-style: normal;" threads="">"10 threads ready to race...\n"
; go(); // go! for (auto& th : threads) th.join(); return 0; }

No comments:

Post a Comment