純Mutex實現多執行緒交替列印

小小bugbug發表於2020-10-12
#include<iostream>
#include<mutex>
#include<string>
#include<thread>
#include<chrono>
using namespace std;
mutex m;
bool PrintFlag = false;
void thread1(const string&s)
{
	size_t i = 0;
	unique_lock<mutex> ul(m);
	while (true)
	{
		if (!ul)
			ul.lock();
		if (PrintFlag)
		{	
			if (i<s.length())
			{
				PrintFlag = !PrintFlag;
				cout.put(s[i]);
				++i;
			}	
		}	
		ul.unlock();
	}
}
void thread2(const string&s)
{
	size_t i = 0;
	unique_lock<mutex> ul(m);
	while (true)
	{
		if (!ul)
			ul.lock();
		if (!PrintFlag)
		{
			if (i < s.length())
			{
				PrintFlag = !PrintFlag;
				cout.put(s[i]);
				++i;
			}
		}
		ul.unlock();
	}
}
int main()
{
	thread td1(thread1, "1234567");
	thread td2(thread2, "ABCDEFG");
	td1.detach();
	td2.detach();
	this_thread::sleep_for(chrono::seconds(10));
	return 0;
}

相關文章