[英]Python and multiprocessing… how to call a function in the main process?
我想在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需要在主進程中調用???
目前還不清楚為什么在這里使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.