上次面试被问到用三个线程循环打印一串字符串,当时没答好,现在一想其实挺简单的,只要用条件变量就好了。使用C++11的标准线程语法,用一个int变量控制条件变量的wait()阻塞等待时机,用notify_all()唤醒条件变量。
具体的代码如下,3个线程分别打印ABC,循环10次:
#include <iostream> #include <thread> #include <condition_variable> std::mutex mtx; std::condition_variable cv; int ready = 0; void PrintString_1() { std::unique_lock<std::mutex> lk(mtx); int cnt = 0; while(cnt<10) { while(ready != 0) cv.wait(lk); std::cout<<std::this_thread::get_id()<<" : "<<"A"<<std::endl; ready = 1; cnt++; cv.notify_all(); } } void PrintString_2() { std::unique_lock<std::mutex> lk(mtx); int cnt = 0; while(cnt<10) { while(ready != 1) cv.wait(lk); std::cout<<std::this_thread::get_id()<<" : "<<"B"<<std::endl; ready = 2; cnt++; cv.notify_all(); } } void PrintString_3() { std::unique_lock<std::mutex> lk(mtx); int cnt = 0; while(cnt<10) { while(ready != 2) cv.wait(lk); std::cout<<std::this_thread::get_id()<<" : "<<"C"<<std::endl; ready = 0; cnt++; cv.notify_all(); } } int main() { std::thread t1(PrintString_1); std::thread t2(PrintString_2); std::thread t3(PrintString_3); t1.join(); t2.join(); t3.join(); return 0; }
运行结果如下: