windows系統調用 semaphore訊號量

來源:互聯網
上載者:User

標籤:style   class   blog   code   color   get   

 1 #include "iostream" 2 #include "windows.h" 3 #include "cstring" 4 using namespace std; 5  6 HANDLE g_hSemThreads=INVALID_HANDLE_VALUE; 7  8 static DWORD WINAPI ThreadProc(LPVOID lpParam){ 9     LONG nPauseMs=reinterpret_cast<LONG>(lpParam);10     Sleep(nPauseMs);11 12     if(g_hSemThreads!=INVALID_HANDLE_VALUE){13         LONG nPrevCt(0);14 15         if(ReleaseSemaphore(16             g_hSemThreads,17             1,18             &nPrevCt19             )){20                 printf("%d msec thread ended ,slots left:%d\n",nPauseMs,nPrevCt+1);21         }22     }23 24     return(0);25 }26 27 28 29 void main(){30     g_hSemThreads=CreateSemaphore(31         NULL,32         5,33         5,34         NULL35         );36     for(int nTotal=20;nTotal>0;nTotal-=2){37         WaitForSingleObject(g_hSemThreads,INFINITE);38         LONG nPauseMs=nTotal*5;39 40         HANDLE hThread=CreateThread(41             NULL,42             0,43             ThreadProc,44             reinterpret_cast<LPVOID>(nPauseMs),45             0,46             NULL47             );48 49         printf("in the %d msec a thread is creates \n",nPauseMs);50         CloseHandle(hThread);51         hThread=INVALID_HANDLE_VALUE;52     }53 54     CloseHandle(g_hSemThreads);55     g_hSemThreads=INVALID_HANDLE_VALUE;56     getchar();57 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.