forked from launchdarkly/python-server-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixed_thread_pool.py
More file actions
63 lines (57 loc) · 1.87 KB
/
Copy pathfixed_thread_pool.py
File metadata and controls
63 lines (57 loc) · 1.87 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from threading import Event, Lock, Thread
import queue
from ldclient.impl.util import log
"""
A simple fixed-size thread pool that rejects jobs when its limit is reached.
"""
class FixedThreadPool:
def __init__(self, size, name):
self._size = size
self._lock = Lock()
self._busy_count = 0
self._event = Event()
self._job_queue = queue.Queue()
for i in range(0, size):
thread = Thread(target = self._run_worker)
thread.name = "%s.%d" % (name, i + 1)
thread.daemon = True
thread.start()
"""
Schedules a job for execution if there is an available worker thread, and returns
true if successful; returns false if all threads are busy.
"""
def execute(self, jobFn):
with self._lock:
if self._busy_count >= self._size:
return False
self._busy_count = self._busy_count + 1
self._job_queue.put(jobFn)
return True
"""
Waits until all currently busy worker threads have completed their jobs.
"""
def wait(self):
while True:
with self._lock:
if self._busy_count == 0:
return
self._event.clear()
self._event.wait()
"""
Tells all the worker threads to terminate once all active jobs have completed.
"""
def stop(self):
for i in range(0, self._size):
self._job_queue.put('stop')
def _run_worker(self):
while True:
item = self._job_queue.get(block = True)
if item == 'stop':
return
try:
item()
except Exception:
log.warning('Unhandled exception in worker thread', exc_info=True)
with self._lock:
self._busy_count = self._busy_count - 1
self._event.set()