2018-04-07 11:44:43 +02:00
|
|
|
"""Helper threading perform all the threading operations."""
|
|
|
|
|
2017-07-10 07:08:10 +02:00
|
|
|
from contextlib import contextmanager
|
2015-11-22 16:18:59 +01:00
|
|
|
import threading
|
2017-07-10 07:08:10 +02:00
|
|
|
|
2017-07-06 19:35:40 +02:00
|
|
|
try:
|
|
|
|
import prctl
|
2018-04-10 10:49:34 +02:00
|
|
|
except ImportError:
|
|
|
|
def set_thread_name(name):
|
|
|
|
"""Set the thread name for external use (visible from the OS)."""
|
|
|
|
threading.current_thread().name = name
|
|
|
|
else:
|
2018-04-07 11:44:43 +02:00
|
|
|
def set_thread_name(name):
|
2018-04-07 15:12:21 +02:00
|
|
|
"""Set a name for the thread for python internal use."""
|
2018-04-07 11:44:43 +02:00
|
|
|
prctl.set_name(name)
|
2017-07-06 19:35:40 +02:00
|
|
|
|
|
|
|
def _thread_name_hack(self):
|
|
|
|
set_thread_name(self.name)
|
|
|
|
threading.Thread.__bootstrap_original__(self)
|
|
|
|
|
|
|
|
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
|
|
|
|
threading.Thread._Thread__bootstrap = _thread_name_hack
|
2018-04-07 11:44:43 +02:00
|
|
|
|
2015-11-22 16:18:59 +01:00
|
|
|
|
|
|
|
class StoppableThread(object):
|
|
|
|
def initStop(self):
|
|
|
|
self.stop = threading.Event()
|
|
|
|
self._stopped = False
|
2018-04-07 11:44:43 +02:00
|
|
|
|
2015-11-22 16:18:59 +01:00
|
|
|
def stopThread(self):
|
|
|
|
self._stopped = True
|
2017-07-06 19:35:40 +02:00
|
|
|
self.stop.set()
|
2017-07-10 07:08:10 +02:00
|
|
|
|
2018-04-07 11:44:43 +02:00
|
|
|
|
2017-07-10 07:08:10 +02:00
|
|
|
class BusyError(threading.ThreadError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def nonBlocking(lock):
|
|
|
|
locked = lock.acquire(False)
|
|
|
|
if not locked:
|
|
|
|
raise BusyError
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
lock.release()
|