zoukankan      html  css  js  c++  java
  • THRDTERM-----干净地结束一个线程

    惊恐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 ");
    return (DWORD)-1;
    }
    }
    printf("PI=%.4g ",(double)inside / i*4);
    return 0;
    }

  • 相关阅读:
    redux-plain-english-workflow
    github入门操作
    debian 安装 android studio 环境
    [转]Linux挂载点介绍及桌面服务器分区方案
    Debian 安装 vmware-tools 手记
    linux 查看进程 和 杀死进程
    extern "C"的用法解析
    TinyXML:一个优秀的C++ XML解析器
    g++ 编译c文件
    python 压缩 解压缩 文件
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/7151444.html
Copyright © 2011-2022 走看看