华为OJ多线程

我用C++11多线程解决该问题,但不完全符合上题要求,大家看看思路就行。

#include 
#include 
#include 
#include 

using namespace std;

char g_write[1032];
mutex mtx;
condition_variable cond1;
condition_variable cond2;
condition_variable cond3;
condition_variable cond4;
bool isFinish = false;

void ThreadFun1(int *n)
{
	for (int i = 0; i < *n;i++)
	{
		unique_lock lock(mtx);
		
		cond4.wait(lock);

		cout << "A";
		lock.unlock();
		cond1.notify_one();
	}
	isFinish=true;
}

void ThreadFunc2(void)
{
	while (!isFinish)
	{
		unique_lock lock(mtx);
		
		cond1.wait(lock);
		
		cout << "B";
		lock.unlock();
		cond2.notify_one();
	}
}

void ThreadFunc3(void)
{
	while (!isFinish)
	{
		unique_lock lock(mtx);

		cond2.wait(lock);

		cout << "C";
		lock.unlock();
		cond3.notify_one();
	}
}

void ThreadFunc4(void)
{
	cond4.notify_all();
	while (!isFinish)
	{
		unique_lock lock(mtx);

		cond3.wait(lock);

		cout << "D";
		lock.unlock();
		cond4.notify_all();
	}
}

void Init(int *n)
{
	thread t1(ThreadFun1, n);
	thread t2(ThreadFunc2);
	thread t3(ThreadFunc3);
	thread t4(ThreadFunc4);

	t1.join();
	t2.join();
	t3.join();
	t4.join();
}

void Release()
{
	isFinish = true;
}

int main(void)
{
	int n;
	cin >> n;

	Init(&n);

	return 0;
}


你可能感兴趣的:(华为OJ)