我想在python中实现异步回调样式函数...这就是我想出来的但我不确定如何实际返回主进程并调用函数。
funcs = {}
def runCallback(uniqueId):
'''
I want this to be run in the main process.
'''
funcs[uniqueId]()
def someFunc(delay, uniqueId):
'''
This function runs in a seperate process and just sleeps.
'''
time.sleep(delay)
### HERE I WANT TO CALL runCallback IN THE MAIN PROCESS ###
# This does not work... It calls runCallback in the separate process:
runCallback(uniqueId)
def setupCallback(func, delay):
uniqueId = id(func)
funcs[uniqueId] = func
proc = multiprocessing.Process(target=func, args=(delay, uniqueId))
proc.start()
return unqiueId
以下是我希望它的工作方式:
def aFunc():
return None
setupCallback(aFunc, 10)
### some code that gets run before aFunc is called ###
### aFunc runs 10s later ###
这里有一个问题,因为我希望这有点复杂。基本上当主进程中的代码完成运行时...我想检查funcs dict然后运行任何尚未运行的回调。这意味着runCallback还需要从funcs dict中删除条目... funcs dict不与单独的进程共享,所以我认为runCallback需要在主进程中调用???
答案 0 :(得分:4)
目前还不清楚为什么在这里使用multiprocessing
模块。
要在同一过程中调用延迟函数,您可以使用threading.Timer
。
threading.Timer(10, aFunc).start()
如果您想稍后取消回调, Timer
有.cancel()
方法:
t = threading.Timer(10, runCallback, args=[uniqueId, funcs])
t.start()
timers.append((t, uniqueId))
# do other stuff
# ...
# run callbacks right now
for t, uniqueId in timers:
t.cancel() # after this the `runCallback()` won't be called by Timer()
# if it's not been called already
runCallback(uniqueId, funcs)
修改runCallback()
以删除要调用的函数:
def runCallback(uniqueId, funcs):
f = funcs.pop(uniqueId, None) # GIL protects this code with some caveats
if f is not None:
f()
答案 1 :(得分:3)