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