代码:
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex my_mutex;
char num = 'a';
const int max_num = 10;
void PrintOdd(){
my_mutex.lock();
while(1){
if(num>'z'){my_mutex.unlock();break;}
if(num%2 == 0){
cout << "thread1:" << num << endl;num++;
}
else{my_mutex.unlock();}
}
}
void PrintEven(){
my_mutex.lock();
while(1){
if(num>'z'){my_mutex.unlock();break;}
if(num%2 == 1){
cout << "thread2:" << num << endl;num++;
}
else{my_mutex.unlock();}
}
}
int main(){
thread t1(PrintOdd);
thread t2(PrintEven);
t1.join();
t2.join();
return 0;
}