线程的快跑与等待

来源:互联网 发布:帝国cms漏洞 编辑:程序博客网 时间:2024/04/28 08:04

今天看的Multithreading Application in Win32  写的一个线程代码,写了下我的注释。另外这本书绝对的经典,侯捷翻译功底也令人叹服.

 

#include <windows.h>
#include 
<stdio.h>
#include 
<string.h>
#include 
<time.h>

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

DWORD WINAPI ThreadPro(LPVOID);

int main(int argc, char *argv[]) 
{    
    HANDLE hThreads[THREAD_POOL_SIZE];
    
int slot=0;
    DWORD threadId;
    
int i;
    DWORD rc;

    
for (i=1;i<=NUM_TASKS;i++)
    
{
        
if (i>THREAD_POOL_SIZE)        //说明当前已经开了3个线程了
        {
            rc
=WaitForMultipleObjects(THREAD_POOL_SIZE,hThreads,FALSE,INFINITE);      //等待一个线程结束
            slot=rc-WAIT_OBJECT_0;         //获取是哪条线程结束
            if (slot>=0&&slot<MAX_THREAD_INDEX)  //这里close掉handle,为重新下面分配做准备
            {
                printf(
"thread %d terminated ",slot);
                CloseHandle(hThreads[slot]);
            }

        }

        hThreads[slot
++]=CreateThread(NULL,0,ThreadPro,(LPVOID)slot,0,&threadId);  //slot(中文意有"通道") 表示当前又开辟的线程  注意可能是才开发的处女地,也可能是上面才释放的一个handle
        printf("Launched thread #%d  slot %d ",i,slot);    
    }


    rc
=WaitForMultipleObjects(THREAD_POOL_SIZE,hThreads,TRUE,INFINITE);   //这里WaitForMultipleObjects第三个参数是true 等待全部线程结束
    for (slot=0;slot<=MAX_THREAD_INDEX;slot++)                                 
    
{
        CloseHandle(hThreads[slot]);
    }

    printf(
"all threads terminated ");

    
return 0;
}


DWORD WINAPI ThreadPro(LPVOID n)
{
    Sleep(
10000);
    printf(
"slot %d idle  ",n);
    
return((DWORD)n);
}

 

原创粉丝点击