/************************************************************************
** Mutex 互斥器
** 学习Mutex和WaitForSingleObject一起使用的方法
**
** 主要函数:
** CreateMutex
** OpenMutex
** ReleaseMutex
** Mutex可以跨进程使用,用途之一防多开
************************************************************************/
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
int a[ 5 ];
const int LOOP_COUNT = 10;
const char * szMutexName = "62634453-F10D-4777-8EE6-C7D1E6325BCF";
UINT __stdcall Thread( void* pParams )
{
int i, num = 1;
HANDLE hThreadMutex = NULL;
hThreadMutex = OpenMutex( MUTEX_ALL_ACCESS, FALSE, szMutexName );
if ( NULL == hThreadMutex )
{
return 0;
}
for ( int k = 0; k < LOOP_COUNT; ++k )
{
cout << "***** thread is blocking *****\n";
WaitForSingleObject( hThreadMutex, INFINITE );
for ( i = 0; i < 5; i++ ) a[ i ] = num;
cout << "***** thread working *****\n";
if ( k == LOOP_COUNT/2 )
{
ExitThread(0);
}
ReleaseMutex( hThreadMutex );
num++;
}
return 0;
}
int main( void )
{
HANDLE hMutex = CreateMutex( NULL, FALSE, szMutexName );
if ( NULL == hMutex || ERROR_ALREADY_EXISTS == ::GetLastError() )
{
cout << "application is already exists!" << endl; //好奇怪,这样为什么不行呢?
return 0;
}
UINT threadID = 0;
HANDLE hHandle = (HANDLE)_beginthreadex( NULL, 0, Thread, NULL, 0, &threadID );
for ( int k = 0; k < LOOP_COUNT; ++k )
{
DWORD dwResult = WaitForSingleObject( hMutex, INFINITE );
switch ( dwResult )
{
case WAIT_OBJECT_0:
{
cout << "***** main working *****\n";
for ( int i = 0; i < 5; ++i )
{
cout << a[i] << " ";
}
cout << endl;
ReleaseMutex( hMutex );
}
break;
case WAIT_ABANDONED:
{
// 另一线程抛弃了它
cout << "***** ABANDONED *****\n";
ReleaseMutex( hMutex );
}
break;
default:
{
cout << dwResult << endl;
}
break;
}
}
return 0;
}