题目:
编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
#include <stdio.h>
#include <windows.h>
#include<iostream>
#include <process.h>
#include <time.h>
using namespace std;
HANDLE g_a, g_b, g_c;
CRITICAL_SECTION g_cs;
unsigned int __stdcall PrintA(void* pM)
{
int i = 0;
while (i < 10)
{
WaitForSingleObject(g_a, INFINITE);
EnterCriticalSection(&g_cs);
cout <<i+1<< ": A";
SetEvent(g_b);
++i;
LeaveCriticalSection(&g_cs);
}
return 0;
}
unsigned int __stdcall PrintB(void* pM)
{
int i = 0;
while (i < 10)
{
WaitForSingleObject(g_b, INFINITE);
EnterCriticalSection(&g_cs);
cout << 'B';
SetEvent(g_c);
++i;
LeaveCriticalSection(&g_cs);
}
return 0;
}
unsigned int __stdcall PrintC(void* pM)
{
int i = 0;
while (i < 10)
{
WaitForSingleObject(g_c, INFINITE);
EnterCriticalSection(&g_cs);
cout << "C\n";
SetEvent(g_a);
++i;
LeaveCriticalSection(&g_cs);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&g_cs);
g_a = CreateEvent(NULL, FALSE, TRUE, NULL);
g_b = CreateEvent(NULL, FALSE, FALSE, NULL);
g_c = CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE threads[3];
threads[0] = (HANDLE)_beginthreadex(NULL, 0, PrintA, NULL, 0, NULL);
threads[1] = (HANDLE)_beginthreadex(NULL, 0, PrintB, NULL, 0, NULL);
threads[2] = (HANDLE)_beginthreadex(NULL, 0, PrintC, NULL, 0, NULL);
WaitForMultipleObjects(3, threads, TRUE, INFINITE);
CloseHandle(g_a);
CloseHandle(g_b);
CloseHandle(g_c);
CloseHandle(threads[0]);
CloseHandle(threads[1]);
CloseHandle(threads[2]);
DeleteCriticalSection(&g_cs);
cout << endl;
system("pause");
return 0;
}原文地址:http://blog.csdn.net/bupt8846/article/details/45541723