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;
    }


  • 相关阅读:
    LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation]
    LeetCode 15 3Sum [sort] <c++>
    LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++>
    LeetCode 33 Search in Rotated Sorted Array [binary search] <c++>
    LeetCode 80 Remove Duplicates from Sorted Array II [Array/auto] <c++>
    将博客搬至CSDN
    leetcode
    (转载) 图像领域常用资源
    Unity3D 之 C# 脚本
    Kinect 人机交互开发实践
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7159341.html
Copyright © 2011-2022 走看看