Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1064209
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-11-02 17:26:11

多线程范例:在程序执行后,主线程等待全部线程结束后退出。 

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

DWORD WINAPI ThreadFun(LPVOID);
#define THREAD_POOL_SIZE 5

int main(){
    HANDLE hThrds[THREAD_POOL_SIZE];
    int slot=0;
    DWORD threadId[THREAD_POOL_SIZE];
    int i;
    DWORD rc;

    for(i=0;i<THREAD_POOL_SIZE;i++){
        hThrds[i]=CreateThread(NULL, 0, ThreadFun, (LPVOID)i, 0, &threadId[i]);
        if(hThrds[i]) {
            printf("Thread %d lanched \n", i);
        }
    }
    
    rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, true, INFINITE);
    
    slot = rc - WAIT_OBJECT_0;
    if(slot>=0 && slot<THREAD_POOL_SIZE) printf("All thread terminite\n");

    for(i=0;i<THREAD_POOL_SIZE;i++){
        CloseHandle(hThrds[i]);
    }
    return 0;
}

DWORD WINAPI ThreadFun(LPVOID n){
    int i;
    for(i=0;i<(int)n;i++){
        Sleep(1000);
    }
    printf("Thread %d terminate\n", n);
    return 0;
}


阅读(2997) | 评论(0) | 转发(0) |
0

上一篇:基本多线程代码

下一篇:互斥锁同步

给主人留下些什么吧!~~