This repository has been archived by the owner on May 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
atomiclong.py
75 lines (59 loc) · 1.99 KB
/
atomiclong.py
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
from cffi import FFI
from functools import total_ordering
ffi = FFI()
ffi.cdef("""
long long_add_and_fetch(long *, long);
long long_sub_and_fetch(long *, long);
long long_bool_compare_and_swap(long *, long, long);
""")
lib = ffi.verify("""
long long_add_and_fetch(long *v, long l) {
return __sync_add_and_fetch(v, l);
};
long long_sub_and_fetch(long *v, long l) {
return __sync_sub_and_fetch(v, l);
};
long long_bool_compare_and_swap(long *v, long o, long n) {
return __sync_bool_compare_and_swap(v, o, n);
};
""")
@total_ordering
class AtomicLong(object):
def __init__(self, initial_value):
self._storage = ffi.new('long *', initial_value)
def __repr__(self):
return '<{0} at 0x{1:x}: {2!r}>'.format(
self.__class__.__name__, id(self), self.value)
@property
def value(self):
return self._storage[0]
@value.setter
def value(self, new):
lib.long_bool_compare_and_swap(self._storage, self.value, new)
def __iadd__(self, inc):
lib.long_add_and_fetch(self._storage, inc)
return self
def __isub__(self, dec):
lib.long_sub_and_fetch(self._storage, dec)
return self
def __eq__(self, other):
# This is needed because between `self.value` and `other.value` being
# evaluated it's possible for the value to be changed (and since this
# is a library predicated on threads being a thing, we have to care
# about such rare race conditions)
if self is other:
return True
elif isinstance(other, AtomicLong):
return self.value == other.value
else:
return self.value == other
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
# See __eq__ for an explanation of why this is a thing.
if self is other:
return False
elif isinstance(other, AtomicLong):
return self.value < other.value
else:
return self.value < other