Python和多处理。。。如何在主进程中调用函数?

Python和多处理。。。如何在主进程中调用函数?,python,multiprocessing,Python,Multiprocessing,我想在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 s

我想在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目录中删除条目。。。funcs dict不与单独的进程共享,因此我认为需要在主进程中调用runCallback

要准确地执行您正试图执行的操作,您需要在父进程中设置一个信号处理程序来运行回调(如果子进程不需要访问父进程的任何内存,则只需删除子进程运行的回调函数),并让子进程发送一个,但如果您的逻辑变得更复杂,您可能需要使用另一种类型的进程间通信(IPC),如或


另一种可能是使用而不是进程,然后您可以从第二个线程运行回调。您需要添加一个来同步对
funcs
指令的访问。

不清楚您为什么在这里使用
多处理
模块

在您可以使用的同一进程中调用具有延迟的函数

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()
def runCallback(uniqueId, funcs):
    f = funcs.pop(uniqueId, None) # GIL protects this code with some caveats
    if f is not None:
       f()