天天看點

利用事件對象同步線程

#include <windows.h> 

#include <stdio.h> 

#define NUMTHREADS 3 

#define BUFFER_SIZE 16 

#define FOR_TIMES 5 

HANDLE hEvent; 

BYTE lpSharedBuffer[16] = {0}; 

void UseEvents(void); 

DWORD WINAPI EventFunction(LPVOID lpParam); 

int main(){ 

    UseEvents(); 

void UseEvents(void){ 

    HANDLE hThread; 

    hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); 

    if(hEvent == NULL){ 

        printf("CreateEvent failed.(%d)\n",GetLastError()); 

        return; 

    } 

    hThread = CreateThread(NULL,0,EventFunction,NULL,0,NULL); 

    if(hThread == NULL){ 

        printf("CreateThread failed.(%d)\n",GetLastError()); 

    Sleep(2000); 

    CopyMemory(lpSharedBuffer,"Event",strlen("Event")); 

    SetEvent(hEvent); 

DWORD WINAPI EventFunction(LPVOID lpParam){ 

    DWORD dwWaitResult; 

    dwWaitResult = WaitForSingleObject(hEvent,INFINITE); 

    if(dwWaitResult!=WAIT_OBJECT_0){ 

        printf("Wait error:%d\n",GetLastError()); 

        return 0; 

    printf("0%x",lpSharedBuffer); 

    system("pause"); 

    if(!ResetEvent(hEvent)){ 

        printf("SetEvent failed(%d)\n",GetLastError()); 

    return 1; 

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