进程中调用CreateMutex 分类: VC++ 2013-10-09 09:13 599人阅读 评论(0) 收藏

// 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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2013-10-09 09:13  毛毛虫的薄刻  阅读(231)  评论(0编辑  收藏  举报