forked from decarbonization/PlayerKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RBLockableObject.h
116 lines (95 loc) · 2.29 KB
/
RBLockableObject.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* RBLockableObject.h
* PlayerKit
*
* Created by James MacWhinnie on 3/19/10.
* Copyright 2010 Roundabout Software. All rights reserved.
*
*/
#ifndef RBLockableObject_h
#define RBLockableObject_h 1
#include "RBObject.h"
#include "RBException.h"
#include <pthread.h>
/*!
@class
@abstract The RBLockableObject class provides a basic object which incorporates
a simple recursive lock, allowing code to gain exclusive access to an object.
*/
class RBLockableObject : public RBObject
{
protected:
mutable pthread_mutex_t mMutex;
pthread_mutexattr_t mMutexAttributes;
public:
#pragma mark Constructor/Destructor
/*!
@abstract The constructor.
*/
RBLockableObject(const char *className = "RBLockableObject");
/*!
@abstract The destructor
*/
virtual ~RBLockableObject();
#pragma mark -
#pragma mark Locking
/*!
@method
@abstract This method should be called when a thread wishes gain exclusive access to an object.
@discussion This method retains the receiver and locks its internal mutex. This method is recursive.
*/
void Acquire() const throw(RBException);
/*!
@method
@abstract Try to acquire exclusive access to the receiver for the current thread.
*/
bool TryToAcquire() const throw(RBException);
/*!
@method
@abstract This method should be called when code no longer requires
exclusive interaction with the receiver.
@discussion This method unlocks the receivers internal mutex, and releases the receiver.
*/
void Relinquish() const throw(RBException);
#pragma mark -
class Acquisitor
{
const RBLockableObject *mObject;
bool mHasAccess;
public:
Acquisitor(const RBLockableObject *object, bool useTry = false) :
mObject(object)
{
if(useTry)
{
mHasAccess = object->TryToAcquire();
}
else
{
object->Acquire();
mHasAccess = true;
}
}
~Acquisitor()
{
if(mHasAccess)
mObject->Relinquish();
}
bool HasAccess() const { return mHasAccess; }
void Relinquish()
{
if(mHasAccess)
{
mObject->Relinquish();
mHasAccess = false;
}
}
private:
Acquisitor(Acquisitor &object);
Acquisitor &operator=(Acquisitor &object);
};
private:
RBLockableObject(RBLockableObject &object);
RBLockableObject &operator=(RBLockableObject &object);
};
#endif /* RBLockableObject_h */