【问题标题】:wait initialized of all threads in pool等待池中所有线程的初始化
【发布时间】:2017-04-29 18:23:50
【问题描述】:

我有创建线程池的主线程。在调用函数之前,对池中的每个线程进行初始化。当所有线程都将被初始化时,如何等待?

例子:

from multiprocessing.pool import ThreadPool

def main():
    # in main thread
    pool = ThreadPool(processes=5, initializer=init_pool)

    # >>> here it is I want to wait for initialized

    pool.map_async(do_smth).get()

 def init_pool():
    # initialized new thread in pool
    pass

def do_smth():
    # do somethings
    pass

如果发生线程初始化异常,则必须不引起map_async

【问题讨论】:

  • 我可以使用多处理中的值来达到这个目的,但这不是很好的解决方案

标签: python multiprocessing threadpool


【解决方案1】:

我会在您的do_smth() 函数中实现barrier 并跳过init_pool。但这只能从 Python 3.2 开始。

Barriers 有预定义的参与方数量,必须调用 Barrier 的 wait-function。当屏障记录正确数量的调用时,它会“丢弃”,调用方会同时返回到那里他们的工作。

类似的东西:

from multiprocessing.pool import ThreadPool
from threading import Barrier

b = Barrier(parties=5)

def main():
    # in main thread
    pool = ThreadPool(processes=5)

    pool.map_async(do_smth).get()

def do_smth():
    #initialize here
    b.wait() #call to the barrier
    # do somethings
    pass

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 2011-12-05
  • 2020-03-27
  • 2019-10-24
  • 2015-08-29
  • 2010-10-16
相关资源
最近更新 更多