天天看點

使用信号量進行線程同步

#include <windows.h> 

#include <stdio.h> 

#define NUMTHREADS 4 

HANDLE hSemaphore; 

void UseSemaphore(void); 

DWORD WINAPI SemaphoreThread(LPVOID lpParam); 

int main(void){ 

    UseSemaphore(); 

void UseSemaphore(void){ 

    HANDLE hThread[NUMTHREADS]; 

    INT i; 

    LONG lMax; 

    CHAR cMax; 

    printf("将建立%d個線程,獲得信号量的線程可以向螢幕列印.\n請輸入信号量的最大計數1-%d:",NUMTHREADS,NUMTHREADS); 

    cMax = getch(); 

    printf("%c\n",cMax); 

    lMax = cMax & 0xF; 

    if(lMax<0 || lMax>NUMTHREADS){ 

        printf("請輸入1-%d.\n",NUMTHREADS); 

    } 

    hSemaphore = CreateSemaphore(NULL,lMax,lMax,NULL); 

    if(hSemaphore == NULL){ 

        printf("Create Semaphorec error.(%d)\n",GetLastError()); 

    for(i=0;i<NUMTHREADS;i++){ 

        hThread[i] = CreateThread(NULL,0,SemaphoreThread,&i,0,NULL); 

        if(hThread[i] == NULL){ 

            printf("Create Threads error.(%d)\n",GetLastError()); 

            return; 

        } 

    WaitForMultipleObjects(NUMTHREADS,hThread,TRUE,INFINITE); 

DWORD WINAPI SemaphoreThread(LPVOID lpParam){ 

    DWORD dwWaitResult; 

    BYTE lpRead[16]; 

    DWORD j = 0; 

    DWORD dwPreviousCount; 

    for(;j<3;j++){ 

        Sleep(rand()%1000); 

        dwWaitResult = WaitForSingleObject(hSemaphore,INFINITE); 

        switch(dwWaitResult){ 

        case WAIT_OBJECT_0: 

            printf("\nProcess %d Gets Semaphore",GetCurrentThreadId()); 

            break; 

        default: 

            printf("\nprocess %u wait error:%u",GetCurrentThreadId(),GetLastError()); 

        if(!ReleaseSemaphore(hSemaphore,1,&dwPreviousCount)) 

        { 

            printf("\nprocess %u Release Semaphore error:%d",GetCurrentProcessId(),GetLastError()); 

        }else 

            printf("\nProcess %u Release Semaphore,previous count is %u",GetCurrentProcessId(),dwPreviousCount); 

    return 1; 

本文轉hackfreer51CTO部落格,原文連結:http://blog.51cto.com/pnig0s1992/673401,如需轉載請自行聯系原作者

繼續閱讀