- #include <windows.h>
- #include <stdio.h>
-
- #define NUM_THREADS 4
-
- DWORD dwCounter = 0;
- HANDLE hMutex;
-
- void UseMutex(void);
- DWORD WINAPI MutexThread(LPVOID lpParam);
-
- int main(void){
- UseMutex();
- }
-
- void UseMutex(void){
- INT i;
- HANDLE hThread;
- hMutex = CreateMutex(NULL,FALSE,NULL);
- if(hMutex == NULL){
- printf("Create mutex error.(%d)\n",GetLastError());
- return;
- }
- for(i=0;i<NUM_THREADS;i++){
- hThread = CreateThread(NULL,0,MutexThread,NULL,0,NULL);
- if(hThread == NULL){
- printf("Create thread error.(%d)\n",GetLastError());
- return;
- }
- }
- Sleep(1000);
- }
-
- DWORD WINAPI MutexThread(LPVOID lpParam){
- DWORD dwMutexResult;
- dwMutexResult = WaitForSingleObject(hMutex,INFINITE);
- switch(dwMutexResult){
- case WAIT_OBJECT_0:
- Sleep(rand()%100);
- printf("counter:%d\n",dwCounter);
- dwCounter++;
- if(!ReleaseMutex(hMutex)){
- printf("Release Mutex error.(%d)\n",GetLastError());
- }
- break;
- default:
- printf("Wait error.(%d)\n",GetLastError());
- ExitProcess(0);
- }
- return 1;
- }
本文转hackfreer51CTO博客,原文链接:http://blog.51cto.com/pnig0s1992/672635,如需转载请自行联系原作者