#define N 6

HANDLE hSuspend[N], hResume[N];
HANDLE hSuspend_one;
HANDLE hResume_one;

struct info


{
CRITICAL_SECTION ProtectSection;
int id;
int frames;
};


unsigned long __stdcall testFun(void *pContext)


{
info* pInfo = (info*)pContext;
while(1)

{
EnterCriticalSection(&pInfo->ProtectSection);
pInfo->frames++;
//printf("run sub Thread video %d frames %d\n", pInfo->id, pInfo->frames);
// DWORD rtn = WaitForSingleObject(hSuspend[pInfo->id], INFINITE);
DWORD rtn = WaitForSingleObject(hSuspend_one, INFINITE);
if (WAIT_OBJECT_0 == rtn)

{// 自己暂停自己
// printf("stop sub Thread video %d frames %d\n", pInfo->id, pInfo->frames);
WaitForSingleObject(hResume[pInfo->id], INFINITE);
//WaitForSingleObject(hResume_one, INFINITE);
}
LeaveCriticalSection(&pInfo->ProtectSection);
}
return 0;
}


int main()


{
DWORD thid;
HANDLE hand[N];
int mainframes = 0;
info myInfo[N];

hSuspend_one = CreateEvent(NULL, TRUE, FALSE, NULL);
for(int i = 0; i < N; i++)

{
hSuspend[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
hResume[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
myInfo[i].id = i;
myInfo[i].frames = 0;
InitializeCriticalSection(&myInfo[i].ProtectSection);
}
for(int i = 0; i < N; i++)

{
hand[i] = CreateThread( NULL, NULL, testFun, &myInfo[i], CREATE_SUSPENDED, &thid);
}

for(int i = 0; i < N; i++)

{
ResumeThread(hand[i]);
}
while(1)

{
printf("main thread frames %d\n", ++mainframes);

/**//*for(int i = 0; i < N; i++)
{
SetEvent(hSuspend[i]);
}*/
SetEvent(hSuspend_one);
Sleep(5);
for(int i = 0; i < N; i++)

{
printf("main thread video %d frames %d\n",myInfo[i].id,myInfo[i].frames);
}
printf("\n");
for(int i = 0; i < N; i++)

{
SetEvent(hResume[i]);
}
}
for(int i = 0; i < N; i++)

{
WaitForSingleObject(hand[i], INFINITE);
DeleteCriticalSection( &myInfo[i].ProtectSection);
CloseHandle(hand[i]);
CloseHandle(hResume[i]);
CloseHandle(hSuspend[i]);
}
CloseHandle(hSuspend_one);
return 0;
}
posted on 2012-04-06 13:32
noBugnoGain 阅读(986)
评论(0) 编辑 收藏 引用