setEvent()

setEvent()  

2010-06-12 15:16:47|  分类: Windows编程|举报|字号 订阅

// setEvent.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
HANDLE zthread = NULL;
HANDLE evtMuti;
HANDLE evtTerminate;

DWORD WINAPI ThreadFunc(void *arg)
{
 int j =0;
 while (1)
 {
  if (WaitForSingleObject(evtTerminate,0) != WAIT_TIMEOUT)
  {
   printf("killed!\n");
   return 0;
  }

  WaitForSingleObject(evtMuti,INFINITE);
  ResetEvent(evtMuti);

  printf("%d\n", j);
  j++;

  Sleep(1);
 }

 
 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 int i;

 char c;
 evtMuti = CreateEvent(NULL, TRUE, FALSE, _T("mutiSet"));
 evtTerminate = CreateEvent(NULL,FALSE, FALSE, _T("TERMINATE"));

 zthread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
 
 for (i = 0; i < 100; i++)
 {
  SetEvent(evtMuti);
  Sleep(1);
 }


 SetEvent(evtTerminate);
// Sleep(1);
 if (WaitForSingleObject(zthread,INFINITE) == WAIT_TIMEOUT)
 {
  TerminateThread(zthread, 2);
 }
 zthread = NULL;
 
 ResetEvent(evtTerminate);

 return 0;
}

for循环中在setEvent之后要Sleep(1)释放CPU,子线程才能获取时间片执行,若不sleep,主线程在执行完for循环之后才能执行子线程,子线程中只得到一个事件,执行一次!

在得到evtTerminate事件时子线程结束返回!

SetEvent多少次,子线程的主循环能执行多少次,这是测试得到的结论!

你可能感兴趣的:(setEvent())