lib: Implement a Thread class
Basically a wrapper around threading.Thread to make things re-runnable Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
This commit is contained in:
parent
2d9502f62a
commit
04e42d0e37
|
@ -0,0 +1,35 @@
|
|||
# Copyright 2021 (c) Anna Schumaker.
|
||||
from . import publisher
|
||||
from . import thread
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
class TestThread(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.started = None
|
||||
self.called = False
|
||||
self.thread = thread.Thread(self.thread_func)
|
||||
|
||||
def thread_func(self):
|
||||
self.assertIsNotNone(self.thread.thread)
|
||||
self.called = True
|
||||
|
||||
def on_thread_start(self, thread):
|
||||
self.started = thread
|
||||
|
||||
def test_thread(self):
|
||||
self.assertIsInstance(thread.Start, publisher.Publisher)
|
||||
thread.Start.register(self.on_thread_start)
|
||||
|
||||
self.assertIsInstance(self.thread.lock, type(threading.Lock()))
|
||||
self.assertEqual(self.thread.func, self.thread_func)
|
||||
self.assertIsNone(self.thread.thread)
|
||||
self.assertFalse(self.thread.running())
|
||||
|
||||
self.assertEqual(self.thread(), self.thread)
|
||||
self.thread.join()
|
||||
|
||||
self.assertTrue(self.called)
|
||||
self.assertFalse(self.thread.running())
|
||||
self.assertEqual(self.started, self.thread)
|
||||
self.assertIsNone(self.thread.thread)
|
|
@ -0,0 +1,35 @@
|
|||
# Copyright 2021 (c) Anna Schumaker.
|
||||
from . import publisher
|
||||
import threading
|
||||
|
||||
Start = publisher.Publisher()
|
||||
|
||||
class Thread:
|
||||
def __init__(self, func):
|
||||
self.func = func
|
||||
self.thread = None
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def __call__(self):
|
||||
with self.lock:
|
||||
if self.thread:
|
||||
return None
|
||||
self.thread = threading.Thread(target = self.__func__)
|
||||
self.thread.start()
|
||||
Start.publish(self)
|
||||
return self
|
||||
|
||||
def __func__(self):
|
||||
self.func()
|
||||
with self.lock:
|
||||
self.thread = None
|
||||
|
||||
def join(self):
|
||||
if self.thread:
|
||||
self.thread.join()
|
||||
|
||||
def running(self):
|
||||
with self.lock:
|
||||
if self.thread:
|
||||
return self.thread.is_alive()
|
||||
return False
|
Loading…
Reference in New Issue