在使用 Python3 创建一个实例后,我如何才能立即做某事?

How I can do something right after one instance created with Python3?

我在 Python3 中使用多处理时遇到问题。我使用多处理读取多个文件并创建读取数据的实例。在读取和创建实例之后,我想要的是在创建一个实例之后立即做某事。但是它并没有像我预期的那样工作。

下面的代码实际上是在等待创建所有实例后运行,然后 do_something 代码被执行。这不是我所期望的。

import multiprocessing
import os
from itertools import repeat

pool = multiprocessing.Pool(processes=3)
pool = multiproccesiin.pool.ThreadPool(processes=1)
events = list(map(lambda x: os.path.split(x)[1].split('.')[0], events))
async_results = pool.startmap_async(Writer,zip(events, repeat(self._settings['TANKDIR']), repeat(self._settings['CATDIR']),repeat(self._settings['DATADIR'])))
# Writer is my class init.
# The earliest created instance takes about 4.5 sec.
tpool.map(do_something, async_results.get())
# I thought tpool.map part start do_something right after one instance created.'

tpool.map(do_something, async_results.get()) 只会将第一个 Writer 实例发送到 do_something 函数。

multiprocessing.map()

This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer.

因此,您使用 tpool.map 调用所做的相当于 do_something(async_result.get()) —— 即。仅将第一个 Writer 发送到 do_something

在不了解您的用例的情况下,解决方案可能就像 tpool.map(do_something, list(async_results))

一样简单