百度空间 | 百度首页 
 
查看文章
 
尽量使用WaitForMultipleObjects替代WaitForSingleObjects
2008-10-07 11:00

WaitForSingleObjects对于Thread数组来说相当于busy loop,因为假设结束顺序和创建顺序是一样的.这就带来了效率问题

/*
written by c4pt0r
for studing WaitForMultipleObjects
*/

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

DWORD WINAPI ThreadFunc(LPVOID);

#define THREAD_POOL_SIZE 3
#define MAX_THREAD_INDEX THREAD_POOL_SIZE-1
#define NUM_TASK 6


int main()
{
HANDLE hThread[THREAD_POOL_SIZE];
int slot=0;
DWORD threadID;
int i;
DWORD exitcode;

for (i=1;i<=NUM_TASK;i++)
{
   if (i > THREAD_POOL_SIZE) //if the number of the running thread is more than the pool size,then we wait
   {
    int rc=WaitForMultipleObjects(THREAD_POOL_SIZE,hThread,false,INFINITE);
    slot=rc - WAIT_OBJECT_0 ;
    printf("slot %d terminated!\n",slot);

   }
   hThread[slot++]=CreateThread(NULL,0,ThreadFunc,(LPVOID)slot,NULL,&threadID);
   printf("Launch %d \n",slot);
  
}
WaitForMultipleObjects(THREAD_POOL_SIZE,hThread,true,INFINITE); //the main thread,wait for every thread

for (slot=0 ; slot<THREAD_POOL_SIZE ; slot++)  
   CloseHandle(hThread[slot]);
printf("All thread terminated!\n");
return EXIT_SUCCESS;
}

DWORD WINAPI ThreadFunc(LPVOID n)
{
srand(GetTickCount());
Sleep((rand()%8*500)+500);
printf("Slot %d idle\n",n);
return (DWORD)n;

}


类别:默认分类 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu