-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadSafeCounter.py
More file actions
39 lines (31 loc) · 1.06 KB
/
Copy pathThreadSafeCounter.py
File metadata and controls
39 lines (31 loc) · 1.06 KB
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
import threading
from AccessViolationException import AccessViolationException
# TODO: Properly use this via with as well.
class ThreadSafeCounter(object):
def __init__(self):
self._count = 0
self._cost = 0.00
self._lock = threading.Lock()
def increment(self, count, cost):
with self._lock:
self._count += count
self._cost += cost
def increment_within_existing_lock(self, count, cost):
if self._lock.locked():
self._count += count
self._cost += cost
else:
raise AccessViolationException("Cannot access unlocked resource!")
def get(self) -> (int, float):
with self._lock:
return (self._count, self._cost)
def get_within_existing_lock(self):
if self._lock.locked():
return (self._count, self._cost)
else:
raise AccessViolationException("Cannot access unlocked resource!")
def __enter__():
self._lock.acquire()
return self
def __exit__():
self._lock.release()