/************************************************************************************* 使用过的两个线程等待技术: Sleep() busy loop 即不断调用GetExitCodeThread()直到其结果不再是STILL_ACTIVE。busy loop通常是可以依赖的,但是有个重大缺陷:浪费CPU时间! *************************************************************************************/ #include #include #include #include DWORD WINAPI ThreadFunc(LPVOID); int main(char argc, char* argv[]) { HANDLE hThrd; DWORD exitCode = 0; DWORD threadId; DWORD begin; DWORD elapsed; puts("Timing normal function call.../n"); 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.../n"); begin = GetTickCount(); hThrd = CreateThread(NULL, 0, ThreadFunc, (LPVOID)1, 0, &threadId); // busy loop for(;;) { GetExitCodeThread(hThrd, &exitCode); if(exitCode != STILL_ACTIVE) { break; } } elapsed = GetTickCount() - begin; printf("function call took: %d.%.03d seconds/n/n", elapsed/1000, elapsed%1000); CloseHandle(hThrd); return EXIT_SUCCESS; } DWORD WINAPI ThreadFunc(LPVOID n) { int i; int inside = 0; double val; srand((unsigned)time(NULL)); for(i=0; i<100000000; 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; }
busy loop
最新推荐文章于 2024-11-15 15:32:24 发布