Advertisement
STANAANDREY

std condition variable ex

Sep 28th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <condition_variable>
  5. #include <vector>
  6. #include <chrono>
  7.  
  8. std::mutex mtx;
  9. std::condition_variable cv;
  10. bool ready = false;
  11.  
  12. void waiter(int id) {
  13.     std::unique_lock<std::mutex> lock(mtx);
  14.     std::cout << "Thread " << id << " waiting\n";
  15.     cv.wait(lock);
  16.     std::cout << "Thread " << id << " awakened\n";
  17. }
  18.  
  19. void signaler() {
  20.     std::this_thread::sleep_for(std::chrono::seconds(1));
  21.     {
  22.         std::lock_guard<std::mutex> lock(mtx);
  23.         ready = true;
  24.     }
  25.     for (int i = 0; i < 3; ++i) {
  26.         std::cout << "Signaling...\n";
  27.         cv.notify_one();
  28.         std::this_thread::sleep_for(std::chrono::milliseconds(100));
  29.     }
  30. }
  31.  
  32. int main() {
  33.     std::vector<std::thread> threads;
  34.     for (int i = 0; i < 5; ++i) {
  35.         threads.emplace_back(waiter, i);
  36.     }
  37.     std::thread s(signaler);
  38.  
  39.     for (auto& t : threads) t.join();
  40.     s.join();
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement