Two wait technologies under windows
First type: Win32 Sleep () function
This function requires the operating system to abort the thread action until it has been read for a specified time before resuming. Can be called at the end of a thread, rather than at the end of a certain period of time.
Second type: Busy loop (busy waits)
Keep calling GetExitCodeThread () until its result is no longer still_active.
Cons: Wasting CPU time.
Never use busy loop in Win32
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 ();//shows the interval of time elapsed after the computer starts in milliseconds.
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));
The inside of this macro is actually a record and explains the results of 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 have a good random number generator (Rand is iffy)
*/
DWORD WINAPI ThreadFunc (lpvoid N)
{
int i;
int inside = 0;
Double Val;
Unreferenced_parameter (n);//Tell the compiler that the variable is already in use and do not have to detect the warning!
/*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;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two wait functions under windows