CreateThread()函数中的第五个参数如果是0的话,那么创建的线程会马上执行。
先来看代码:
#define WIN32_LEAN_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>
#include "../../MtVerify.h"
DWORD WINAPI ThreadFunc(LPVOID);
HANDLE hRequestExitEvent=false;
int main()
{
HANDLE hThreads[2];
DWORD dwThreadId;
DWORD dwExitCode=0;
int i;
hRequestExitEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
for (int i = 0; i < 2; i++)
{
MTVERIFY(hThreads[i]=CreateThread(NULL,0,ThreadFunc,(LPVOID)i,0,&dwThreadId));
}
Sleep(1000);
SetEvent(hRequestExitEvent);
WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);
for (int i = 0; i < 2; i++)
{
MTVERIFY(CloseHandle(hThreads[i]));
}
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadFunc(LPVOID p)
{
int i;
int inside=0;
UNREFERENCED_PARAMETER(p);
srand((unsigned)time(NULL));
for ( i = 0; i < 1000000; i++)
{
double x=(double)(rand())/RAND_MAX;
double y=(double)(rand())/RAND_MAX;
if ((x*x+y*y)<=1.0)
{
inside++;
}
SetEvent(hRequestExitEvent);
if (WaitForSingleObject(hRequestExitEvent,0)!=WAIT_TIMEOUT){printf("Received request to terminate\n");return (DWORD)-1;}}printf("PI=%.4g\n",(double)inside/i*4);return 0;}
代码执行结果是打印出两行PI=3.142
如果我们把
SetEvent(hRequestExitEvent);
这句代码放到
Sleep(1000);
的前面一行,那么执行结果就是两行Received request to terminate
因为在执行两条工作线程的时候,事件已经被激活。