Fixed main use case

This commit is contained in:
2020-06-21 16:09:54 -07:00
parent f3b7713d0e
commit 997d07a0c4

29
bg.py
View File

@@ -7,6 +7,7 @@ Implement a simple parallel work class.
# Uses low level threading.
import sys
import time
import _thread as _t
class NotReadyError(RuntimeError):
@@ -30,25 +31,27 @@ class Bg:
def __init__(self, func, *args, **kwarg):
assert callable(func)
self._running = _t.allocate_lock()
self._tid = _t.start_new_thread(self.run, args, kwarg)
def run(self, func, args, kwarg):
"Acquire locks, start thread, return thread id"
self._running.acquire()
try:
self._result = func(*args, **kwarg)
## Create inner function to run in a thread.
def _job():
"Run requested callable in a thread"
self._running.acquire()
self.start = time.time()
except:
self._exc_info = sys.exc_info()
finally:
self.finish = time.time()
self._running.release()
try:
self._result = func(*args, **kwarg)
except:
self._exc_info = sys.exc_info()
finally:
self._running.release()
# Store the thread id in an instance variable.
self._tid = _t.start_new_thread(_job, ())
def running(self):
def is_running(self):
"Return True if the job is still running"
return self._running.locked()
def done(self):
def is_done(self):
"Return True if the job finished running"
return not self._running.locked()