三个线程交替执行,c++实现

作为前一篇文章http://blog.csdn.net/don_lvsml/article/details/21003835 两个线程的交替执行,现在扩展为三个线程直接的交替执行。

代码如下:

#pragma once
#include
#include
#include
using namespace std;

int g_t=0;
HANDLE g_hThreadEvent1;
CRITICAL_SECTION g_csThreadCode1;
HANDLE event0;
HANDLE event1;
HANDLE event2;
bool flag0 = false;
bool flag1 = true;
bool flag2 = false;

unsigned int __stdcall Fun3(void* pPM)
{
	int nThreadID=*(int *)pPM;
	SetEvent(g_hThreadEvent1);
	Sleep(50);
	
	for(int i=0;i<10;++i)
	{	
		if(nThreadID==0)
		{
			SetEvent(event1);//激活另外一个线程	
			WaitForSingleObject(event0,INFINITE);
			while(!flag0)
				Sleep(1);
			EnterCriticalSection(&g_csThreadCode1);
			//ResetEvent(event0);
			cout<<"C";
			flag0 = false;
			flag1 = true;
			LeaveCriticalSection(&g_csThreadCode1);
			Sleep(50);//一定要阻塞当前线程一定时间,不然在某一个会死锁。保证其他线程能执行。
		}
		else if(nThreadID==1)
		{
			SetEvent(event2);
			WaitForSingleObject(event1,INFINITE);
			while(!flag1)
				Sleep(1);
			EnterCriticalSection(&g_csThreadCode1);
			//ResetEvent(event1);
			cout<<"A";
			flag1 = false;
			flag2 = true;
			LeaveCriticalSection(&g_csThreadCode1);
			Sleep(50);
		}
		else if(nThreadID==2)
		{
			SetEvent(event0);
			WaitForSingleObject(event2,INFINITE);
			while(!flag2)
				Sleep(1);
			EnterCriticalSection(&g_csThreadCode1);
			//ResetEvent(event2);
			cout<<"B";
			flag2 = false;
			flag0 = true;
			LeaveCriticalSection(&g_csThreadCode1);			
			Sleep(50);
		}
	}
	return 0;
}

//三个进程交替进行打印 
void alternateExe3()
{
	const int num = 3;
	HANDLE handle[num];
	g_hThreadEvent1 = CreateEvent(NULL,false,false,NULL);
	event0 = CreateEvent(NULL,false,false,NULL);
	event1 = CreateEvent(NULL,false,false,NULL);
	event2 = CreateEvent(NULL,false,false,NULL);
	InitializeCriticalSection(&g_csThreadCode1);
	int i=0;
	while(i
在main函数中调用alternateExe3()即可实现。

实现原理与两个线程一致,都是通过设置标识量来完成,而且在当前线程中触发下一线程。

结果为



你可能感兴趣的:(多线程编程)