C++ 11 三個執行緒列印ABC(順序列印)
阿新 • • 發佈:2018-12-31
題目:有3個執行緒A,B, C, 請用多執行緒程式設計實現在螢幕上迴圈列印10次ABCABC..., 其中A執行緒列印“A”, B執行緒列印“B”, C執行緒列印“C”。
使用C++11 實做, 程式碼如下:
#include <iostream> #include <thread> #include <condition_variable> #include <vector> #include <algorithm> std::mutex mtx; std::condition_variable cvar; char g_ch = 0; void print_fun(char ch) { int cyle_cnt = 10; char ch_ = ch - 'A'; for (int i = 0; i < cyle_cnt; i++) { std::unique_lock<std::mutex>ulk(mtx); cvar.wait(ulk, [ch_] {return ch_ == g_ch; }); std::cout << (char)(ch_ + 'A'); g_ch = (ch_ + 1) % 3; ulk.unlock(); cvar.notify_all(); } } int main() { std::vector<std::thread> threads; threads.push_back(std::thread(print_fun, 'A')); threads.push_back(std::thread(print_fun, 'B')); threads.push_back(std::thread(print_fun, 'C')); std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); std::cout << std::endl; system("pause"); return 0; }