开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上,要求输出结果必须按ABC的顺序显示:ABCABC

第四题(迅雷笔试题):编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
#include    
#include    
#include    
#define  g_hThreadEvent(n) g_hThreadEvent##1

unsigned int __stdcall Fun(void *pPM);  
//线程个数
const int THREAD_NUM = 8;  

//循环次数
const int LOOP = 6;

//互斥事件
HANDLE g_hThreadEvent[THREAD_NUM];


int main()
{
	printf("\t子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环10 次,\n接着再回到主线程又循环 100 次,如此循环50次\n");

	int i = 0 , j;
	HANDLE hdl[THREAD_NUM];


	for (i = 0; i < THREAD_NUM; i++) 
		g_hThreadEvent[i] = CreateEvent(NULL,FALSE,FALSE,NULL);

	//将线程编号作为线程参数传进去,先转换为指针,再转换为整形,
	for (i = 0; i < THREAD_NUM; i++) 
		hdl[i] = (HANDLE)_beginthreadex(NULL,0,Fun,(void*)i,0,NULL);

	
	SetEvent(g_hThreadEvent[0] );


	WaitForMultipleObjects(THREAD_NUM,hdl,TRUE,INFINITE);

	for (i = 0; i < THREAD_NUM; i++)
	{
		CloseHandle(hdl[i]);
		CloseHandle(g_hThreadEvent[i]);
	}

	return 0;
}

unsigned int __stdcall Fun(void *pPM)
{
	int num = (int)pPM;
	int i = 0;

	for( i  = 0 ; i< LOOP;i++)
	{
		WaitForSingleObject(g_hThreadEvent[num],INFINITE);
		
		//printf("  线程ID=%d,线程编号是%c ,%d \n",GetCurrentThreadId(),num+'A');	 
		 printf(" %c ",num+'A');

		 if(num+1 == THREAD_NUM )
			 printf(" \n");
		
		SetEvent(g_hThreadEvent[(num+1)%THREAD_NUM]);
	}
	return 0;
}

你可能感兴趣的:(windows编程,C++)