THRDTERM-----干净地结束一个线程
2015-07-24 18:22
411 查看
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;
}
相关文章推荐
- js添加input节点,删除input节点
- 使用CURL出现certificate verify failed错误的解决方法
- C#:实现接口中定义的事件
- Weka连接数据库出现No suitable driver found for jdbc:mysql://localhost/dbname
- 335x挂载不上ubi一些问题的解决
- Docker 问题总结
- hdu 5303 Delicious Apples(背包)
- java图书管理的一个小模块(增删改查,不使用数据库)
- Linux 系统挂载数据盘
- 我做的产品规划
- iOS引用图片文件的三种方式
- Java的一些基础笔试题
- SQLite3(创建、插入、查询、更新数据库和表)
- Jquery text() 和html使用
- 图像处理之膨胀腐蚀操作
- java中计算坐标的相关算法
- Shell脚本练习题
- [转]把汉字写“绝”了
- Prime Palindromes (数据加强版)
- Codeforces Gym 100637A A. Nano alarm-clocks 前缀和