-
Notifications
You must be signed in to change notification settings - Fork 2
/
RBLockableObject.cpp
71 lines (57 loc) · 2.06 KB
/
RBLockableObject.cpp
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
/*
* RBLockableObject.cpp
* PlayerKit
*
* Created by James MacWhinnie on 3/19/10.
* Copyright 2010 Roundabout Software. All rights reserved.
*
*/
#include "RBLockableObject.h"
RBLockableObject::RBLockableObject(const char *className) :
RBObject(className),
mMutex((pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER)
{
int errorCode = pthread_mutexattr_init(&mMutexAttributes);
RBAssertNoErr(errorCode, CFSTR("pthread_mutexattr_init failed with error code %d"), errorCode);
errorCode = pthread_mutexattr_settype(&mMutexAttributes, PTHREAD_MUTEX_RECURSIVE);
RBAssertNoErr(errorCode, CFSTR("pthread_mutexattr_settype failed with error code %d"), errorCode);
errorCode = pthread_mutex_init(&mMutex, &mMutexAttributes);
RBAssertNoErr(errorCode, CFSTR("pthread_mutex_init failed with error code %d"), errorCode);
}
RBLockableObject::~RBLockableObject()
{
int errorCode = pthread_mutex_destroy(&mMutex);
RBAssertNoErr(errorCode, CFSTR("pthread_mutexattr_destroy failed with error code %d"), errorCode);
errorCode = pthread_mutexattr_destroy(&mMutexAttributes);
RBAssertNoErr(errorCode, CFSTR("pthread_mutexattr_destroy failed with error code %d"), errorCode);
}
#pragma mark -
#pragma mark Locking
void RBLockableObject::Acquire() const throw(RBException)
{
int errorCode = pthread_mutex_lock(&mMutex);
RBAssertNoErr(errorCode, CFSTR("pthread_mutex_unlock failed with error %d"), errorCode);
this->Retain();
}
bool RBLockableObject::TryToAcquire() const throw(RBException)
{
int errorCode = pthread_mutex_trylock(&mMutex);
if(errorCode == noErr)
{
this->Retain();
return true;
}
else if(errorCode != EBUSY)
{
RBAssertNoErr(errorCode, CFSTR("pthread_mutex_trylock failed with error %d"), errorCode);
}
return false;
}
void RBLockableObject::Relinquish() const throw(RBException)
{
int errorCode = pthread_mutex_unlock(&mMutex);
//We eat EPERM errors because this method is a no-op when the receiver is not locked.
if(errorCode != 0 && errorCode != EPERM)
RBAssertNoErr(errorCode, CFSTR("pthread_mutex_unlock failed with error %d"), errorCode);
this->Release();
}