1 回答
TA贡献1784条经验 获得超9个赞
如果您需要立即杀死,您可以使用 amultiprocessing.Event通知父进程满足条件并让它立即杀死工作进程。管理器进程对于这种需要的少量同步来说太重了。
import os
from datetime import datetime
from multiprocessing import Process, Event
def worker(range_, target, found_event):
print('{} | pid: {} started'.format(datetime.now(), os.getpid()))
for x in range_:
if x == target:
print('{} | pid: {} found target'.format(
datetime.now(), os.getpid())
)
found_event.set()
if __name__ == "__main__":
N_WORKERS = 4
step = int(200e6)
ranges = [range(x, x + step) # change `range` to `xrange` for Python 2
for x in range(0, N_WORKERS * step, step)]
# range(0, 200000000), ..., range(800000000, 1000000000)]
target = int(150e6) # <-- worker finding this value triggers massacre
found_event = Event()
pool = [Process(target=worker, args=(range_, target, found_event))
for range_ in ranges]
for p in pool:
p.start()
found_event.wait() # <- blocks until condition met
print('{} | terminating processes'.format(datetime.now()))
for p in pool:
p.terminate()
for p in pool:
p.join()
print('{} | all processes joined'.format(datetime.now()))
示例输出:
2019-01-17 01:55:33.781884 | pid: 28376 started
2019-01-17 01:55:33.782333 | pid: 28377 started
2019-01-17 01:55:33.782851 | pid: 28378 started
2019-01-17 01:55:33.783484 | pid: 28379 started
2019-01-17 01:55:54.715425 | pid: 28376 found target
2019-01-17 01:55:54.715613 | terminating processes
2019-01-17 01:55:54.716326 | all processes joined
Process finished with exit code 0
添加回答
举报