-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.h
79 lines (66 loc) · 1.16 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* THOR - THOR Template Library
* Joshua M. Kriegshauser
*
* mutex.h
*
* Defines a platform-agnostic mutex class
*/
#ifndef THOR_MUTEX_H
#define THOR_MUTEX_H
#pragma once
#ifndef THOR_BASE_TYPES_H
#include "basetypes.h"
#endif
#if defined(_WIN32)
#include "win/mutex_win.inl"
#else
#error Unsupported platform!
#endif
namespace thor
{
class mutex : private internal::mutex_base
{
THOR_DECLARE_NOCOPY(mutex);
public:
mutex(size_type spin_count = 4000);
~mutex();
bool lock();
bool try_lock();
bool unlock();
};
///////////////////////////////////////////////////////////////////////////////
template<class T> class scope_locker
{
THOR_DECLARE_NOCOPY(scope_locker);
T& lockable_;
bool locked_;
public:
scope_locker(T& lockable)
: lockable_(lockable)
, locked_(false)
{
lock();
}
~scope_locker()
{
unlock();
}
void lock()
{
if (!locked_)
{
lockable_.lock();
locked_ = true;
}
}
void unlock()
{
if (locked_)
{
lockable_->unlock();
locked_ = false;
}
}
};
}
#endif