两个线程交替打印0到100
#include <mutex> #include <thread> #include <condition_variable> #include <iostream> using namespace std; int num = 0; mutex mtx; condition_variable cv1; void printA() { while(1) { unique_lock<mutex> lck(mtx); cv1.wait(lck, [](){return (num & 0x01) == 0;}); if(num > 100) { cv1.notify_one(); break; } cout << "threadA : " << num++ << endl; cv1.notify_one(); } } void printB() { while(1) { unique_lock<mutex> lck(mtx); cv1.wait(lck, [](){return (num & 0x01) == 1;}); if(num > 100) { num++; cv1.notify_one(); break; } cout << "threadB : " << num++ << endl; cv1.notify_one(); } } int main() { thread t1(printA); thread t2(printB); t1.join(); t2.join(); cout << "all thread zohngzhi " << endl; return 0; }
#笔试题目#