我正在实现一个进程,我想在Manager.list()达到一定数量时停止它,我该怎么做?
我的代码在这里,它不只是工作,有人可以帮助吗?我不想使用线程。
from multiprocessing import current_process, cpu_count
from multiprocessing import Pool, Manager
import sys
# noinspection PyBroadException
def pool_process(value, _results):
"""
Spreading work across a pool of Python Processes
:param value: to be worked on
:param _results: the array that holds them
"""
try:
_results.append(value)
except:
print "FATAL: %s running pool_process(%s, %s) exited with %s" % \
(current_process().name, value, _results, sys.exc_info())
if __name__ == '__main__':
pool = Pool(processes=cpu_count() * 2)
pool_mgr = Manager()
results = pool_mgr.list()
for each in xrange(0, 1000):
pool.apply_async(pool_process, [each, results])
check = True
while check:
if len(pool_mgr.list()) == 100:
check = False
pool.close()
pool.join()
print len(pool_mgr)
答案 0 :(得分:1)
我建议你尝试两件事:
if len(results) >= 100:
和
try:
if len(_results) < 100:
_results.append(value)
except:
问题是您正在并行处理。所以这些交易可能会发生:
if len(results) == 100: # 99
_results.append(value)
_results.append(value)
if len(results) == 100: # 101
你想不仅要停在100,而且你不想要超过100的值。所以你应该使用&gt; =符号。