【发布时间】:2020-01-16 07:17:59
【问题描述】:
我一直在尝试使用 ThreadPoolExecutor 进行多线程,如果其中一个进程满足某个条件,则可以安全地停止执行,这样剩余的线程就不必最终确定。
我有以下概念,但它不起作用,它一直在运行:
import time, sys
from concurrent.futures import ThreadPoolExecutor
data = {"future1": 'blank', "future2": 'blank', "future3": 'blank'}
def function1(n):
global data #not sure if this is necessary, as it seems to be able to access this anyway?
print(n)
time.sleep(1)
data['future1'] = n
def function2(n):
global data
print(n)
time.sleep(2)
data['future2'] = n
def function3(n):
global data
print(n)
time.sleep(3)
data['future3'] = n
with ThreadPoolExecutor(max_workers=4) as executor:
while True:
future1=executor.submit(function1, 'test1')
future2=executor.submit(function2, 'test2')
future3=executor.submit(function3, 'test3')
if data['future2']!='blank':
executor.shutdown(wait=False)
sys.exit()
不知道我在这里做错了什么,任何帮助将不胜感激。
【问题讨论】:
标签: python multithreading concurrency threadpoolexecutor