summaryrefslogtreecommitdiff
path: root/Runtime/Threads/Mutex.h
blob: 91e9927b388d64496496590e7c068083d968e0d4 (plain)
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
80
81
82
83
84
85
86
#ifndef __MUTEX_H
#define __MUTEX_H

#if SUPPORT_THREADS

#if UNITY_WIN || UNITY_XENON
#	include "Winapi/PlatformMutex.h"
#elif UNITY_OSX || UNITY_IPHONE || UNITY_ANDROID || UNITY_PEPPER || UNITY_LINUX || UNITY_BB10 || UNITY_TIZEN
#	include "Posix/PlatformMutex.h"
#else
#	include "PlatformMutex.h"
#endif

#include "Runtime/Utilities/NonCopyable.h"

/**
 *	A mutex class. Always recursive (a single thread can lock multiple times).
 */
class Mutex : public NonCopyable
{
public:
	
	class AutoLock
	{
	public:
		AutoLock( Mutex& mutex )
		: m_Mutex(&mutex)
		{
			mutex.Lock();
		}
		
		~AutoLock()
		{
			m_Mutex->Unlock();
		}
		
	private:
		AutoLock(const AutoLock&);
		AutoLock& operator=(const AutoLock&);
		
	private:
		Mutex*	m_Mutex;
	};

	Mutex();
	~Mutex();
	
	void Lock();
	void Unlock();

	// Returns true if locking succeeded
	bool TryLock();

	// Returns true if the mutex is currently locked
	bool IsLocked();
	
	void BlockUntilUnlocked();

private:
	
	PlatformMutex	m_Mutex;
};

#else

// Used for threadsafe refcounting
class Mutex
{
public:
	
	class AutoLock
	{
	public:
		AutoLock( Mutex& mutex ){}
		~AutoLock()	{}
	};

	bool TryLock () { return true; }
	void Lock () {  }
	void Unlock () {  }
	bool IsLocked () { return false; }
	void BlockUntilUnlocked() {  }
};

#endif //SUPPORT_THREADS
#endif