C++ 多线程编程 condition

xiaoxiao2021-02-28  39

condition_variable wait wait_for wait_unitl notify_one notify_all // condition_variable example #include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; bool ready = false; void print_id (int id) { std::unique_lock<std::mutex> lck(mtx); while (!ready) cv.wait(lck); // ... std::cout << "thread " << id << '\n'; } void go() { std::unique_lock<std::mutex> lck(mtx); ready = true; cv.notify_all(); } int main () { std::thread threads[10]; // spawn 10 threads: for (int i=0; i<10; ++i) threads[i] = std::thread(print_id,i); std::cout << "10 threads ready to race...\n"; go(); // go! for (auto& th : threads) th.join(); return 0; } condition_variable_any wait wait_for wait_unitl notify_one notify_all // condition_variable_any::wait (with predicate) #include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex #include <condition_variable> // std::condition_variable_any std::mutex mtx; std::condition_variable_any cv; int cargo = 0; bool shipment_available() {return cargo!=0;} void consume (int n) { for (int i=0; i<n; ++i) { mtx.lock(); cv.wait(mtx,shipment_available); // consume: std::cout << cargo << '\n'; cargo=0; mtx.unlock(); } } int main () { std::thread consumer_thread (consume,10); // produce 10 items when needed: for (int i=0; i<10; ++i) { while (shipment_available()) std::this_thread::yield(); mtx.lock(); cargo = i+1; cv.notify_one(); mtx.unlock(); } consumer_thread.join(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-2614193.html

最新回复(0)