两个线程交替打印奇数和偶数,一直到10。
用mutex来实现。参考的网上的代码。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int number;
mutex mutex_1;
const int MAXNUM = 10;
void printOdd() {
while (1) {
mutex_1.lock();
if (number >= MAXNUM) {
mutex_1.unlock();
break;
}
if (number % 2 == 0) {
number++;
cout << "mythread_1: " << number << endl;
}
mutex_1.unlock();
}
cout << "mythread_1 finish" << endl;
}
void printEven() {
while (1) {
mutex_1.lock();
if (number >= MAXNUM) {
mutex_1.unlock();
break;
}
if (number % 2 == 1) {
number++;
cout << "mythread_2: " << number << endl;
}
mutex_1.unlock();
}
cout << "mythread_2 finish" << endl;
}
int main() {
number = 0;
cout << endl << "Create and Start!" << endl;
thread mythread_1(printOdd);
thread mythread_2(printEven);
mythread_1.join();
mythread_2.join();
cout << endl << "Finish and Exit!" << endl;
return 0;
}
362

被折叠的 条评论
为什么被折叠?



