CreateMutex理解

// TestStorage.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <process.h>

//#define MUTEX_DBG

UINT WINAPI Thread1(LPVOID para)
{
#ifdef MUTEX_DBG
 HANDLE* phMutex = (HANDLE*)para;

 WaitForSingleObject(*phMutex,INFINITE);
#endif
  printf("Enter Thread1/n");
  printf("I'm sleeping……/n");
  
  Sleep(1000);
  
  printf("Leave Thread1/n");

#ifdef MUTEX_DBG
 ReleaseMutex(*phMutex);
#endif

 return 0;
}
UINT WINAPI Thread2(LPVOID para)
{
#ifdef MUTEX_DBG
 HANDLE* phMutex = (HANDLE*)para;

 WaitForSingleObject(*phMutex,INFINITE);
#endif
 
  printf("Enter Thread2/n");
  printf("I'm sleeping……/n");
  
  Sleep(1000);
  
  printf("Leave Thread2/n");
 
#ifdef MUTEX_DBG
 ReleaseMutex(*phMutex);
#endif
 
 return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
 HANDLE hMutex = NULL;
#ifdef MUTEX_DBG
 hMutex = CreateMutex(NULL,FALSE,NULL);
#endif

 HANDLE hThread1 = (HANDLE)::_beginthreadex(NULL,0,Thread1,&hMutex,0,NULL);
 HANDLE hThread2 = (HANDLE)::_beginthreadex(NULL,0,Thread2,&hMutex,0,NULL);

 Sleep(4000);

 if(hThread1)
  CloseHandle( hThread1 );

 if(hThread2)
  CloseHandle( hThread2 );

 return 0;
}

你可能感兴趣的:(CreateMutex理解)