码迷,mamicode.com
首页 > Windows程序 > 详细

windows下的两个等待函数

时间:2015-07-23 12:05:50      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

技术分享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\n\n", 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\n", 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\n", val * 4);
return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

windows下的两个等待函数

标签:

原文地址:http://blog.csdn.net/wangfengfan1/article/details/47017417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!