Rename project to 'Bg'
This commit is contained in:
@@ -1,25 +1,32 @@
|
||||
#!python3
|
||||
"""
|
||||
go_do.py
|
||||
========
|
||||
bg.py
|
||||
=====
|
||||
Implement a simple parallel work class.
|
||||
"""
|
||||
# Uses low level threading.
|
||||
import sys
|
||||
import time
|
||||
import _thread as _t
|
||||
|
||||
class NotReadyError(RuntimeError):
|
||||
"Job is still running"
|
||||
|
||||
class Do:
|
||||
class Bg:
|
||||
"""
|
||||
Easy to use multi-threading.
|
||||
Run a job in the background.
|
||||
|
||||
>>> job = Bg(func, arg1, arg2, ..., kwarg1=val1, kwarg2=...)
|
||||
"""
|
||||
_tid = None
|
||||
_running = None
|
||||
_result = None
|
||||
_exc_info = None
|
||||
|
||||
# Start and finish timestamp of the job.
|
||||
start = None
|
||||
finish = None
|
||||
|
||||
def __init__(self, func, *args, **kwarg):
|
||||
assert callable(func)
|
||||
self._running = _t.allocate_lock()
|
||||
@@ -30,28 +37,31 @@ class Do:
|
||||
self._running.acquire()
|
||||
try:
|
||||
self._result = func(*args, **kwarg)
|
||||
self.start = time.time()
|
||||
except:
|
||||
self._exc_info = sys.exc_info()
|
||||
finally:
|
||||
self.finish = time.time()
|
||||
self._running.release()
|
||||
|
||||
def done(self):
|
||||
"Return True if the job finished running"
|
||||
return not self._running.locked()
|
||||
|
||||
def running(self):
|
||||
"Return True if the job is still running"
|
||||
return self._running.locked()
|
||||
|
||||
def wait_for_it(self, _timeout=-1):
|
||||
"Wait for the result to be available"
|
||||
def done(self):
|
||||
"Return True if the job finished running"
|
||||
return not self._running.locked()
|
||||
|
||||
def wait(self, _timeout=-1):
|
||||
"Wait for the job to finish"
|
||||
if self._running.acquire(True, _timeout):
|
||||
self._running.release()
|
||||
return self._result
|
||||
raise NotReadyError("Exceeded the timeout")
|
||||
|
||||
@property
|
||||
def result(self):
|
||||
"Return the result if available, raise NotReadyError if not"
|
||||
"Return the result if available, else raise NotReadyError"
|
||||
if self._running.acquire(False):
|
||||
self._running.release()
|
||||
return self._result
|
||||
Reference in New Issue
Block a user