我想将文本输入到 python 并并行处理它。为此,我使用multiprocessing.Pool. 问题是有时,并非总是如此,我必须在处理任何内容之前多次输入文本。
这是我重现问题的代码的最小版本:
import multiprocessing as mp
import time
def do_something(text):
print('Out: ' + text, flush=True)
# do some awesome stuff here
if __name__ == '__main__':
p = None
while True:
message = input('In: ')
if not p:
p = mp.Pool()
p.apply_async(do_something, (message,))
Run Code Online (Sandbox Code Playgroud)
发生的情况是我必须多次输入文本才能得到结果,无论我在第一次输入内容后等待多久。(如上所述,这不会每次都发生。)
python3 test.py
In: a
In: a
In: a
In: Out: a
Out: a
Out: a
Run Code Online (Sandbox Code Playgroud)
如果我在 while 循环之前创建池,或者如果我time.sleep(1)在创建池之后添加,它似乎每次都有效。注意:我不想在获得输入之前创建池。
有人对这种行为有解释吗?
我正在使用 Python 3.4.2 运行 Windows 10 编辑:与 Python 3.5.1 相同的行为
编辑: …
我的问题如下:
Given a number of 2n points, I can calculate the distance between all points
and get a symmetrical matrix.
Can you create n pairs of points, so that the sum of the distance of all pairs is
minimal?
EDIT: Every point has to be in one of the pairs. Which means that
every point is only allowed to be in one pair.
Run Code Online (Sandbox Code Playgroud)
我天真地试图使用匈牙利语算法,并希望它可以给我一个作业,以便作业是对称的.但这显然不起作用,因为我没有二分图.
搜索之后,我发现了稳定的室友问题,这似乎与我的问题类似,但不同的是,它只是试图找到一个匹配,但不是试图最小化某种距离.
有谁知道类似的问题甚至解决方案?我错过了什么?问题实际上看起来并不那么困难,但我无法想出最佳解决方案.