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

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-11-02 20:17:18

 

互斥锁同步多线程:

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

DWORD WINAPI ThreadFun(LPVOID);
#define THREAD_POOL_SIZE 5
HANDLE hMutex;

static int count;

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


    hMutex = CreateMutex(NULL, false, _T("Demo Mutex"));
    
    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");

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

DWORD WINAPI ThreadFun(LPVOID n){
    for(;;){
        WaitForSingleObject(hMutex, INFINITE);
        if(count==20){
            ReleaseMutex(hMutex);
            return 0;
        }
        count++;
        printf("t%d do %d\n", n, count);
        ReleaseMutex(hMutex);
        Sleep(100);
    }
    printf("Thread %d terminate\n", n);
    return 0;
}


阅读(546) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~