THRDTERM-----干净地结束一个线程
2017-07-11 16:58
190 查看
THRDTERM产生两个线程。周期性地检查一个event对象。以决定要不要结束自己。
#define WIN32_LEAN_AND_MEAN
#include<stdio.h>#include<windows.h>
#include<stdlib.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 (i = 0; i < 2; i++)
{
MTVERIFY(hThreads[i] = CreateThread(NULL, 0, ThreadFunc,
(LPVOID)i, 0, &dwThreadId));
}
//wait around for a while, make sure the thread is running
Sleep(1000);
SetEvent(hRequestExitEvent);
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
for (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);
//seed the random-number generator
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++;
}
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;
}
相关文章推荐
- THRDTERM-----干净地结束一个线程
- android 如何结束一个线程
- JAVA里面如何让一个线程死亡或结束
- java中,如何安全的结束一个正在运行的线程?
- 如何强制结束一个线程
- Win32多线程之等待一个线程的结束(WaitForSingleObject)
- vb.net中如何结束一个线程
- 一个线程的产生与结束
- JAVA里面如何让一个线程死亡或结束
- 对tomcat来说,每一个进来的请求(request)都需要一个线程,直到该请求结束。
- 对tomcat来说,每一个进来的请求(request)都需要一个线程,直到该请求结束
- java中,如何安全的结束一个正在运行的线程?
- 对tomcat来说,每一个进来的请求(request)都需要一个线程,直到该请求结束。
- java程序中,如何安全的结束一个正在运行的线程?
- java中,如何安全的结束一个正在运行的线程?
- JAVA里面如何让一个线程死亡或结束
- JAVA里面如何让一个线程死亡或结束
- iOS 如何创建一个线程,要求可以一直工作,不会执行一次就结束
- java程序中,如何安全的结束一个正在运行的线程
- .net C#线程连接Join的技巧,如何真正让一个线程结束,另外一个线程启动