【发布时间】:2017-11-14 15:41:34
【问题描述】:
作为this question 的后续行动,我有一个简单的脚本,它启动threadpoolexecutor 以读取json 文件。这样做时,我想使用 for 循环将其从 1 计数到 9。出于某种原因,即使我使用了executor.shutdown(wait=False),它仍然会阻塞并等待read_employees 方法执行。
如果 wait 为 False,则此方法将立即返回,并且当所有未决的期货执行完毕后,与执行器关联的资源将被释放
import concurrent.futures
import json
import time
def read_employees(read_file):
with open(read_file) as f_obj:
employees = json.load(f_obj)
for emp in employees:
print(emp)
time.sleep(3)
def start_thread():
filename = 'employee.json'
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(read_employees, filename)
executor.shutdown(wait=False)
def print_number():
for num in range(1,10):
time.sleep(2)
print(num)
start_thread()
print_number()
如果我这样做:
def read_employees(read_file):
with open(read_file) as f_obj:
employees = json.load(f_obj)
for emp in employees:
time.sleep(5)
print(emp)
def print_number():
for num in range(1,10):
print(num)
filename = 'employee.json'
empThread = threading.Thread(target=read_employees, args=(filename,))
empThread.start()
print_number()
先从 1 数到 9,然后打印出员工,延迟是因为在阅读员工时睡觉。像这样:
1
2
3
4
5
6
7
8
9
ams@yourcompanyname.com
bcs@yourcompanyname.com
如何在不阻塞的情况下使用threadpoolexecutor 实现相同的输出?
【问题讨论】:
标签: python multithreading threadpoolexecutor