// -, (Windows)
class CAutoMutex
{
//
HANDLE m_h_mutex;
//
CAutoMutex( const CAutoMutex&);
CAutoMutex& operator =( const CAutoMutex&);
public :
CAutoMutex()
{
m_h_mutex = CreateMutex(NULL, FALSE, NULL);
assert(m_h_mutex);
}
~CAutoMutex() { CloseHandle(m_h_mutex); }
HANDLE get () { return m_h_mutex; }
};
* This source code was highlighted with Source Code Highlighter .
// -, (Unix)
class CAutoMutex
{
pthread_mutex_t m_mutex;
CAutoMutex( const CAutoMutex&);
CAutoMutex& operator =( const CAutoMutex&);
public :
CAutoMutex()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
~CAutoMutex()
{
pthread_mutex_destroy(&m_mutex);
}
pthread_mutex_t& get ()
{
return m_mutex;
}
};
* This source code was highlighted with Source Code Highlighter .
// -,
class CMutexLock
{
HANDLE m_mutex;
//
CMutexLock( const CMutexLock&);
CMutexLock& operator =( const CMutexLock&);
public :
//
CMutexLock(HANDLE mutex): m_mutex(mutex)
{
const DWORD res = WaitForSingleObject(m_mutex, INFINITE);
assert(res == WAIT_OBJECT_0);
}
//
~CMutexLock()
{
const BOOL res = ReleaseMutex(m_mutex);
assert(res);
}
};
* This source code was highlighted with Source Code Highlighter .
// ,
#define SCOPE_LOCK_MUTEX(hMutex) CMutexLock _tmp_mtx_capt(hMutex);
* This source code was highlighted with Source Code Highlighter .
//
static CAutoMutex g_mutex;
//
static DWORD g_common_cnt = 0;
static DWORD g_common_cnt_ex = 0;
* This source code was highlighted with Source Code Highlighter .
void do_sth_1( ) throw ()
{
// ...
//
// ...
{
//
SCOPE_LOCK_MUTEX(g_mutex. get ());
//
g_common_cnt_ex = 0;
g_common_cnt = 0;
//
}
// ...
//
// ...
}
* This source code was highlighted with Source Code Highlighter .
void do_sth_1_eq( ) throw ()
{
//
if (WaitForSingleObject(g_mutex. get (), INFINITE) == WAIT_OBJECT_0)
{
//
g_common_cnt_ex = 0;
g_common_cnt = 0;
//
ReleaseMutex(g_mutex. get ());
}
else
{
assert(0);
}
}
* This source code was highlighted with Source Code Highlighter .
// -
struct Ex {};
// ,
int do_sth_2( const int data ) throw (Ex)
{
// ...
//
// ...
//
SCOPE_LOCK_MUTEX(g_mutex. get ());
int rem = data % 3;
if (rem == 1)
{
g_common_cnt_ex++;
//
throw Ex();
}
else if (rem == 2)
{
//
g_common_cnt++;
return 1;
}
//
return 0;
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/72929/