C++|C++ 3个线程顺序输出1-9

3个线程,顺序输出123456789

#include #include #include #include #include #include using namespace std; int g_num = 0; mutex myMutex; condition_variable cv1, cv2, cv3; void thread_Func1() { int a = 0; while (true) { a = -1; { unique_lockguard(myMutex); { while (a % 3 != 1 || a == - 1) { cv1.wait(guard); a = g_num; } } } cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " <guard(myMutex); { while (a % 3 != 2 || a == -1) { cv2.wait(guard); a = g_num; } } } cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " << a << endl; if (a == 8) break; } }void thread_Func3() { int a = 0; while (true) { a = -1; { unique_lockguard(myMutex); { while (a % 3 != 0 || a == -1 ) { cv3.wait(guard); a = g_num; } } } cout << " thread_id : " << std::this_thread::get_id() <<" g_numer : " << a << endl; if (a == 9) break; } } void thread_ctl() { int a = 0; while (a < 9) { { unique_lockguard(myMutex); a = ++g_num; } if (a % 3 == 1) cv1.notify_one(); else if (a % 3 == 2) cv2.notify_one(); else cv3.notify_one(); Sleep(1000); } }int main() { std::thread threadFunc1(thread_Func1); std::thread threadFunc2(thread_Func2); std::thread threadFunc3(thread_Func3); std::thread threadCtl(thread_ctl); threadFunc1.join(); threadFunc2.join(); threadFunc3.join(); threadCtl.join(); return 0; }

【C++|C++ 3个线程顺序输出1-9】C++|C++ 3个线程顺序输出1-9
文章图片

    推荐阅读