zoukankan      html  css  js  c++  java
  • windows下的两个等待函数

    尴尬windows下的两个等待技术

    第一种: Win32  Sleep()函数

         这个函数要求操作系统中止线程动作。直到读过某个指定的时间之后才恢复。能在某个线程结束时(而不是某段时间结束时)被调用。

    另外一种:busy  loop(busy waits)

         不断调用GetExitCodeThread(),直到其结果不再是STILL_ACTIVE.

        缺点:浪费CPU时间。

        绝对不要在Win32中使用busy loop

    //busywait.c
    /*Domonstrate the effect on performance of using a busy loop.
    First call the worker routine with just a function call to get a baseline performance reading 
    then create a second thread and a busy loop.
    */
    #define WIN32_LEAN_AND_MEAN
    #include <stdio.h>
    #include<stdlib.h>
    #include<windows.h>
    #include<time.h>
    #include "MtVerify.h"

    DWORD WINAPI ThreadFunc(LPVOID);

    int main()
    {
    HANDLE hThrd;
    DWORD exitCode = 0;
    DWORD threadId;
    DWORD begin;
    DWORD elapsed;
    puts("TImiing normal function call.....");
    begin = GetTickCount();//示以毫秒为单位的计算机启动后经历的时间间隔。


    ThreadFunc(0);
    elapsed = GetTickCount() - begin;
    printf("Function call took:%d.%.03d seconds ", elapsed / 1000, elapsed % 1000);
    puts("Timing thread + busy loop....");
    begin = GetTickCount();
    MTVERIFY(hThrd = CreateThread(NULL, 0, ThreadFunc, (LPVOID)1, 0, &threadId));
    //这个宏内部事实上是记录并解释了Win32 GetLastError()的结果。
    /*This busy loop chews up lots of CPU time*/
    for (;;)
    {
    GetExitCodeThread(hThrd, &exitCode);
    if (exitCode != STILL_ACTIVE)
    break;
    }
    elapsed = GetTickCount() - begin;
    printf("Thread+busy loop took: %d.%.03d seconds ", elapsed / 1000, elapsed % 1000);
    MTVERIFY(CloseHandle(hThrd));
    return EXIT_SUCCESS;
    }
    /*Cute little busy work routine that computes the value
    of PI using probability.Highly dependent on having a good random number generator (rand is iffy)
    */
    DWORD WINAPI ThreadFunc(LPVOID n)
    {
    int i;
    int inside = 0;
    double val;
    UNREFERENCED_PARAMETER(n);//告诉编译器,已经使用了该变量,不必检測警告。
    /*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++;
    }
    val = (double)inside / i;
    printf("PI=%.4g ", val * 4);
    return 0;
    }


  • 相关阅读:
    jquery ui autocomplete
    解决IIS服务和用户上传的文件分别部署在不同的电脑上时,解决权限的问题
    wpf一些例子
    t-sql 笔记(2)
    t-sql 笔记(1)
    测试基础之软件测试模型
    测试用例设计方法之错误猜测法
    测试用例设计方法之边界值分析法
    批处理文件将多台连接的手机安装同一个APP
    安卓和IOS抓包工具
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7159341.html
Copyright © 2011-2022 走看看