多线程同步打印ABC

以下为三个线程分别打印A、B和C,代码中采用Event来同步线程,保证按照ABC的顺序循环打印。

同志们若有更好的做法,请指教,谢谢!

附:这里有问题,对于线程关闭最好的做法是自然结束,但是工作中常常遇到的是需要线程函数中来个while,哪位兄弟能兼容解决这个问题? 请不吝赐教!~

 

#include <conio.h>
#include <windows.h>
#include <iostream>
using namespace std;

DWORD WINAPI DealThreadA(void* para)
{
	HANDLE handle = *(HANDLE*)para;
	while (1)
	{
		WaitForSingleObject(handle, INFINITE);

		cout<<"A.."<<endl;

		ResetEvent(handle);
	}

	return 0;
}

DWORD WINAPI DealThreadB(void* para)
{
	HANDLE handle = *(HANDLE*)para;
	while (1)
	{
		WaitForSingleObject(handle, INFINITE);

		cout<<"B.."<<endl;

		ResetEvent(handle);
	}

	return 0;
}

DWORD WINAPI DealThreadC(void* para)
{
	HANDLE handle = *(HANDLE*)para;
	while (1)
	{
		WaitForSingleObject(handle, INFINITE);

		cout<<"C.."<<endl<<endl;

		ResetEvent(handle);
	}

	return 0;
}

bool IsEventHasSignal(HANDLE handle)
{
	if(WAIT_OBJECT_0 == WaitForSingleObject(handle, 0))
		return true;

	return false;
}

void WaitEventSignalBeResponsed(HANDLE handle)
{
	while (IsEventHasSignal(handle))
		Sleep(1);
}

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hA = CreateEvent(NULL, TRUE, FALSE, NULL);
	HANDLE hB = CreateEvent(NULL, TRUE, FALSE, NULL);
	HANDLE hC = CreateEvent(NULL, TRUE, FALSE, NULL);

	CreateThread(0, 0, DealThreadA, (void*)&hA, 0, 0);
	CreateThread(0, 0, DealThreadB, (void*)&hB, 0, 0);
	CreateThread(0, 0, DealThreadC, (void*)&hC, 0, 0);

	while (!_kbhit())
	{
		Sleep(1000);

		SetEvent(hA);
		WaitEventSignalBeResponsed(hA);

		SetEvent(hB);
		WaitEventSignalBeResponsed(hB);

		SetEvent(hC);
		WaitEventSignalBeResponsed(hC);
	}

	CloseHandle(hA);
	CloseHandle(hB);
	CloseHandle(hC);

	return 0;
}

你可能感兴趣的:(多线程同步打印ABC)