マルチスレッド循環印刷ABC

10089 ワード

#include
#include
#include
#include
#include

std::mutex mx;
std::condition_variable cond1, cond2, cond3;
int cnt = 0;

void func1() {
	while (true) {
		std::unique_lock<std::mutex> lock(mx);
		cond1.wait(lock, []() {return cnt == 0; });
		++cnt;
		std::cout << "a";
		cond2.notify_one();
	}
}
void func2() {
	while (true) {
		std::unique_lock<std::mutex> lock(mx);
		cond2.wait(lock, []() {return cnt == 1; });
		++cnt;
		std::cout << "b";
		cond3.notify_one();
	}
}
void func3() {
	while (true) {
		std::unique_lock<std::mutex> lock(mx);
		cond3.wait(lock, []() {return cnt == 2; });
		cnt = 0;
		std::cout << "c";
		cond1.notify_one();
	}
}
int main() {
	std::vector<std::thread>threads;
	threads.push_back(std::thread(func1));
	threads.push_back(std::thread(func2));
	threads.push_back(std::thread(func3));
	for (int i = 0; i < threads.size(); ++i) {
		if (threads[i].joinable())
			threads[i].join();
	}
}