Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <vector>
- #include <chrono>
- std::mutex mtx;
- std::condition_variable cv;
- bool ready = false;
- void waiter(int id) {
- std::unique_lock<std::mutex> lock(mtx);
- std::cout << "Thread " << id << " waiting\n";
- cv.wait(lock);
- std::cout << "Thread " << id << " awakened\n";
- }
- void signaler() {
- std::this_thread::sleep_for(std::chrono::seconds(1));
- {
- std::lock_guard<std::mutex> lock(mtx);
- ready = true;
- }
- for (int i = 0; i < 3; ++i) {
- std::cout << "Signaling...\n";
- cv.notify_one();
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- }
- }
- int main() {
- std::vector<std::thread> threads;
- for (int i = 0; i < 5; ++i) {
- threads.emplace_back(waiter, i);
- }
- std::thread s(signaler);
- for (auto& t : threads) t.join();
- s.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement