等待初始化池中的所有线程
问题描述:
我有创建ThreadPool的主线程。在调用函数之前,使初始化池中的每个线程。所有线程将被初始化时如何等待?等待初始化池中的所有线程
例子:
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如果发生
答
一个线程异常的初始化我会实现你的do_smth()
- 函数一个barrier并跳过init_pool
。但是这只能从Python 3.2开始。
障碍具有预定义数量的参与方必须调用障碍的功能wait
。当屏障登记正确的呼叫数量时,它会“下降”,呼叫方同时返回到他们的工作。
类似的东西:
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
+0
酷,谢谢!尽管我用Python 2.7编写,但您的答案对我有帮助! 我可以模拟这样的障碍 http://stackoverflow.com/a/26703365/4181533 – deniska369
我可以使用值从多处理用于此目的,但它是不漂亮的解决方案 – deniska369