//用的是线程、互斥锁、条件变量

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

mutex _mutex;			//定义锁变量
condition_variable cv;			//定义条件变量
int flag = 0;			//切换线程的标识符,flag:0-2分别对应A-B

void printa() {
	unique_lock<mutex> lk(_mutex);		//加锁为了保护flag能被正确访问
	for (int i = 0; i < 10; i++) {
		while (flag != 0) cv.wait(lk);
		cout << "A" << endl;
		flag = 1;
		cv.notify_all();
	}
	cout << "thread 1 print A finish" << endl;
}

void printb() {
	unique_lock<mutex> lk(_mutex);
	for (int i = 0; i < 10; i++) {
		while (flag != 1) cv.wait(lk);
		cout << "B" << endl;
		flag = 2;
		cv.notify_all();
	}
	cout << "thread 2 print B finish" << endl;
}

void printc() {
	unique_lock<mutex> lk(_mutex);
	for (int i = 0; i < 10; i++) {
		while (flag != 2) cv.wait(lk);
		cout << "C" << endl;
		flag = 0;
		cv.notify_all();
	}
	cout << "thread 3 print C finish" << endl;
}

int main() {
	thread th1(printa);
	thread th2(printb);
	thread th3(printc);

	th1.join();
	th2.join();
	th3.join();

	cout << "print all finish" << endl;
}

posted on 2024-03-29 11:35  孜孜不倦fly  阅读(61)  评论(0编辑  收藏  举报