def defer(f=None, predicate=None):
"""
Schedule a function to run in a cpu_bound thread, returns a AsyncFuture
Optional predicate parameter to determine if the function should be dispatched
"""
if f is None:
def p_wrap(f):
return defer(f, predicate)
return p_wrap
else:
def f_wrap(f, *args, **kwargs):
if CPUThread._thread is None:
CPUThread._thread = CPUThread()
return CPUThread._thread.apply(f, args, kwargs)
def wrapper(*args, **kwargs):
a = AsyncFuture(None, None)
# TODO: unit test this
if (predicate is not None and not predicate) or utils.in_cpubound_thread():
v = f(*args, **kwargs)
a._value = v
else:
g = Greenlet(f_wrap, f, *args, **kwargs)
g.start()
a._future = g
return a
return wrapper
评论列表
文章目录