加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:17:36 所属栏目:Python 来源:网络整理
导读:我想在 python中实现一个异步回调样式函数…这是我想出的但我不知道如何实际返回主进程并调用该函数. funcs = {} def runCallback(uniqueId): ''' I want this to be run in the main process. ''' funcs[uniqueId]()def someFunc(delay,uniqueId): ''' This
我想在 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需要在主进程中调用???

解决方法

目前还不清楚为什么在这里使用多处理模块.

要在同一过程中调用具有延迟功能,可以使用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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读