-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread_handler.py
More file actions
53 lines (42 loc) · 1.47 KB
/
Copy paththread_handler.py
File metadata and controls
53 lines (42 loc) · 1.47 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
# -*-: coding utf-8 -*-
""" Thread handler. """
import threading
import time
from singleton import Singleton
from usb_utils import USB
class ThreadHandler(Singleton):
""" Thread handler. """
def __init__(self):
""" Initialisation. """
self.thread_pool = []
self.run_events = []
def run(self, target, args=()):
""" Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function.
"""
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args + (run_event, ))
self.thread_pool.append(thread)
self.run_events.append(run_event)
thread.start()
def start_run_loop(self, logger=None):
""" Start the thread handler, ensuring that everything stops property
when sending a keyboard interrup.
"""
try:
if logger is not None:
logger.debug("Starting run loop thread")
while 1:
time.sleep(.1)
except KeyboardInterrupt:
if logger is not None:
logger.debug("Exiting run loop thread on KeyboardInterrupt")
self.stop()
def stop(self):
""" Stop all functions running in the thread handler."""
for run_event in self.run_events:
run_event.clear()
for thread in self.thread_pool:
thread.join()