池中的工作线程不是在调用pool.apply_async或其他池方法时创建的,而是在实例化池之前创建的。对池方法的调用使用池中现有的线程。在
如果不操作源代码,就无法在初始化时命名线程。您的选择是:在池准备好实例化之后重命名工作线程
monkey修补池内部以强制执行特定的命名模板
第一个选项很容易实现,只需迭代池实例的._pool-属性,并更改所包含线程的.name:from multiprocessing.pool import ThreadPool as Pool
if __name__ == '__main__':
pool = Pool(4)
print([w.name for w in pool._pool])
# ['Thread-1', 'Thread-2', 'Thread-3', 'Thread-4']
for w in pool._pool:
w.name = w.name.replace('Thread', 'ThreadPoolWorker')
print([w.name for w in pool._pool])
# ['ThreadPoolWorker-1', 'ThreadPoolWorker-2', 'ThreadPoolWorker-3', 'ThreadPoolWorker-4']
pool.close()
pool.join()
注意我在这里使用multiprocessing.pool.ThreadPool,只是为了符合下面第二个选项中的示例,因为multiprocessing.dummy.Pool只是ThreadPool的包装。在
对于第二个选项,可以用包装器修补工作线程ThreadPool.Process的工厂函数,用更有意义的名称(如“ThreadPoolWorker”)扩展默认名称“Thread-%d”(%d填充计数器的值)。在
^{pr2}$
用法:from threadpool import ThreadPool as Pool
if __name__ == '__main__':
pool = Pool(4)
print([w.name for w in pool._pool])
# ['ThreadPoolWorker-1', 'ThreadPoolWorker-2', 'ThreadPoolWorker-3', 'ThreadPoolWorker-4']
pool.close()
pool.join()