利用事件对象同步线程

 

  
  
  
  
  1. #include <windows.h> 
  2. #include <stdio.h> 
  3.  
  4. #define NUMTHREADS 3 
  5. #define BUFFER_SIZE 16 
  6. #define FOR_TIMES 5 
  7.  
  8. HANDLE hEvent; 
  9. BYTE lpSharedBuffer[16] = {0}; 
  10.  
  11. void UseEvents(void); 
  12. DWORD WINAPI EventFunction(LPVOID lpParam); 
  13.  
  14. int main(){ 
  15.     UseEvents(); 
  16.  
  17. void UseEvents(void){ 
  18.     HANDLE hThread; 
  19.     hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); 
  20.     if(hEvent == NULL){ 
  21.         printf("CreateEvent failed.(%d)\n",GetLastError()); 
  22.         return
  23.     } 
  24.     hThread = CreateThread(NULL,0,EventFunction,NULL,0,NULL); 
  25.     if(hThread == NULL){ 
  26.         printf("CreateThread failed.(%d)\n",GetLastError()); 
  27.         return
  28.     } 
  29.     Sleep(2000); 
  30.     CopyMemory(lpSharedBuffer,"Event",strlen("Event")); 
  31.     SetEvent(hEvent); 
  32.  
  33. DWORD WINAPI EventFunction(LPVOID lpParam){ 
  34.     DWORD dwWaitResult; 
  35.     dwWaitResult = WaitForSingleObject(hEvent,INFINITE); 
  36.     if(dwWaitResult!=WAIT_OBJECT_0){ 
  37.         printf("Wait error:%d\n",GetLastError()); 
  38.         return 0; 
  39.     } 
  40.     printf("0%x",lpSharedBuffer); 
  41.     system("pause"); 
  42.     if(!ResetEvent(hEvent)){ 
  43.         printf("SetEvent failed(%d)\n",GetLastError()); 
  44.         return 0; 
  45.     } 
  46.     return 1; 

 

你可能感兴趣的:(线程,事件,职场,同步,休闲)