-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMutex.h
65 lines (51 loc) · 1.94 KB
/
Mutex.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* Distributed under the BSD license (http://opensource.org/licenses/BSD-2-Clause) *
* Copyright (c) 2012-2019, Rostislav Kuratch *
* All rights reserved. */
#pragma once
/*! \brief
* A synchronization primitive for multithreaded applications.
* Multiple Get() method calls from one process will not lead to deadlock,
* in other words the mutex is reentrant.
*/
class Mutex
{
public:
//! Mutex is acquired on Scoped_Lock construction and released on destruction.
class Scoped_Lock
{
public:
//! Constructor, takes in reference to Mutex object that will be controlled.
Scoped_Lock( Mutex& mutex ):
mutex_( mutex )
{
mutex_.Get();
}
//! Destructor, releases Mutex object.
virtual ~Scoped_Lock() { mutex_.Release(); }
protected:
Mutex& mutex_;
};
//! Constructor, creates unnamed Mutex object.
Mutex() { InitializeCriticalSection( &cs_ ); }
~Mutex() { DeleteCriticalSection( &cs_ ); }
/*! \brief
* Gets the mutex. If it is not free then waits (blocking) for specified timeout
* and either gets the mutex or returns an error. If no error was encountered returns 0.
* Please note that timeout value has no effect now because it is not implemented.
*/
unsigned int Get( unsigned int timeout = INFINITE )
{
timeout = timeout;
EnterCriticalSection( &cs_ );
return 0;
}
//! Releases the mutex allowing other threads to access the mutex-protected resource.
unsigned int Release()
{
LeaveCriticalSection( &cs_ );
return 0;
}
protected:
CRITICAL_SECTION cs_;
Mutex( Mutex& );
};