forked from peter-iakovlev/Signals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SAtomic.m
93 lines (78 loc) · 1.68 KB
/
SAtomic.m
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
#import "SAtomic.h"
#import <pthread.h>
@interface SAtomic ()
{
pthread_mutex_t _lock;
pthread_mutexattr_t _attr;
bool _isRecursive;
id _value;
}
@end
@implementation SAtomic
- (instancetype)initWithValue:(id)value
{
self = [super init];
if (self != nil)
{
pthread_mutex_init(&_lock, NULL);
_value = value;
}
return self;
}
- (instancetype)initWithValue:(id)value recursive:(bool)recursive {
self = [super init];
if (self != nil)
{
_isRecursive = recursive;
if (recursive) {
pthread_mutexattr_init(&_attr);
pthread_mutexattr_settype(&_attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&_lock, &_attr);
} else {
pthread_mutex_init(&_lock, NULL);
}
_value = value;
}
return self;
}
- (void)dealloc {
if (_isRecursive) {
pthread_mutexattr_destroy(&_attr);
}
pthread_mutex_destroy(&_lock);
}
- (id)swap:(id)newValue
{
id previousValue = nil;
pthread_mutex_lock(&_lock);
previousValue = _value;
_value = newValue;
pthread_mutex_unlock(&_lock);
return previousValue;
}
- (id)value
{
id previousValue = nil;
pthread_mutex_lock(&_lock);
previousValue = _value;
pthread_mutex_unlock(&_lock);
return previousValue;
}
- (id)modify:(id (^)(id))f
{
id newValue = nil;
pthread_mutex_lock(&_lock);
newValue = f(_value);
_value = newValue;
pthread_mutex_unlock(&_lock);
return newValue;
}
- (id)with:(id (^)(id))f
{
id result = nil;
pthread_mutex_lock(&_lock);
result = f(_value);
pthread_mutex_unlock(&_lock);
return result;
}
@end