Windows多线程按顺序打印ABC

#include 
#include 
#include 

const int NUM = 3;
int nCount = 0;

HANDLE g_Mutex = NULL;
HANDLE g_Event = NULL;

unsigned int WINAPI ThreadProc(LPVOID lParam)
{
	int nParam = (int)lParam;
	char c = 'A' + nParam;

	for(int i = 0; i < 10; i++)
	{
		WaitForSingleObject(g_Mutex,INFINITE);

		while( nParam != nCount )
		{
			ReleaseMutex(g_Mutex);
			WaitForSingleObject(g_Mutex,INFINITE);
		}

		printf("%c ", c);
		nCount = (nCount+1)%NUM;

		ReleaseMutex(g_Mutex);
	}

	return TRUE;
}

int main()
{
	g_Event = CreateEvent(NULL, TRUE, FALSE, NULL);
	g_Mutex = CreateMutex(NULL, FALSE, "TEST");

	HANDLE threads[NUM] = {NULL};
	threads[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (void *)0, 0, NULL);
	threads[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (void *)1, 0, NULL);
	threads[2] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (void *)2, 0, NULL);

	WaitForMultipleObjects(NUM, threads, TRUE, INFINITE);

	CloseHandle(threads[0]);
	CloseHandle(threads[1]);
	CloseHandle(threads[2]);
	memset(threads, 0, sizeof(HANDLE)*NUM);

	CloseHandle(g_Mutex);
	CloseHandle(g_Event);
	g_Mutex = NULL;
	g_Event = NULL;
	return 0;
}

你可能感兴趣的:(C++)