conditional variables code in c 2b 2b

Solutions on MaxInterview for conditional variables code in c 2b 2b by the best coders in the world

showing results for - "conditional variables code in c 2b 2b"
Leane
05 Oct 2019
1// condition_variable example
2#include <iostream>           // std::cout
3#include <thread>             // std::thread
4#include <mutex>              // std::mutex, std::unique_lock
5#include <condition_variable> // std::condition_variable
6
7std::mutex mtx;
8std::condition_variable cv;
9bool ready = false;
10
11void print_id (int id) {
12  std::unique_lock<std::mutex> lck(mtx);
13  while (!ready) cv.wait(lck);
14  // ...
15  std::cout << "thread " << id << '\n';
16}
17
18void go() {
19  std::unique_lock<std::mutex> lck(mtx);
20  ready = true;
21  cv.notify_all();
22}
23
24int main ()
25{
26  std::thread threads[10];
27  // spawn 10 threads:
28  for (int i=0; i<10; ++i)
29    threads[i] = std::thread(print_id,i);
30
31  std::cout << "10 threads ready to race...\n";
32  go();                       // go!
33
34  for (auto& th : threads) th.join();
35
36  return 0;
37}