迅雷笔试题

  编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC.依次递推。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>  
#include <string>  
#include <stack>  
#include <windows.h>  
#include <process.h>  
using namespace std;  

HANDLE hEventA;
HANDLE hEventB;
HANDLE hEventC;

HANDLE hThreadA;
HANDLE hThreadB;
HANDLE hThreadC;

UINT __stdcall ThreadA(LPVOID lparam)
{
	int n = 10;
	while(n--)
	{
		WaitForSingleObject(hEventA, INFINITE);
		printf("A");
		ResetEvent(hEventA);
		SetEvent(hEventB);
	}
	return 1;
}

UINT __stdcall ThreadB(LPVOID lparam)
{
	int n = 10;
	while(n--)
	{
		WaitForSingleObject(hEventB, INFINITE);
		printf("B");
		ResetEvent(hEventB);
		SetEvent(hEventC);
	}
	return 1;
}

UINT __stdcall ThreadC(LPVOID lparam)
{
	int n = 10;
	while(n--)
	{
		WaitForSingleObject(hEventC, INFINITE);
		printf("C\n");
		ResetEvent(hEventC);
		SetEvent(hEventA);
	}
	return 1;
}

int main()  
{  
	hEventA = CreateEvent(NULL, TRUE, FALSE, NULL);
	hEventB = CreateEvent(NULL, TRUE, FALSE, NULL);
	hEventC = CreateEvent(NULL, TRUE, FALSE, NULL);
	SetEvent(hEventA);
	hThreadA = (HANDLE)_beginthreadex(NULL, 0, ThreadA, NULL, 0, NULL);
	hThreadB = (HANDLE)_beginthreadex(NULL, 0, ThreadB, NULL, 0, NULL);
	hThreadC = (HANDLE)_beginthreadex(NULL, 0, ThreadC, NULL, 0, NULL);
	WaitForSingleObject(hThreadA, INFINITE);
	WaitForSingleObject(hThreadB, INFINITE);
	WaitForSingleObject(hThreadC, INFINITE);
	CloseHandle(hThreadA);
	CloseHandle(hThreadB);
	CloseHandle(hThreadC);
	CloseHandle(hEventA);
	CloseHandle(hEventB);
	CloseHandle(hEventC);
	return 0;  
}  

  

posted on 2013-05-26 10:44  lzm风雨无阻  阅读(345)  评论(0编辑  收藏  举报

导航