futures
# 使用方法一:
def display(*args):
print(strftime('[%H:%M:%S]'), end=' ')
print(*args)
def loiter(n):
msg = '{}loiter({}): doing nothing for {}s...'
display(msg.format('\t' * n, n, n))
sleep(n)
msg = '{}loiter({}): done'
display(msg.format('\t' * n, n))
return n * 10
def main():
print('Script starting')
with futures.ThreadPoolExecutor(max_workers=3) as executor: # max_workers=3: 指定线程池中的线程数
results = executor.map(loiter, range(5)) # 将 0~4 传递给loiter函数,返回一个迭代器
display('results:', results)
for i, result in enumerate(results): # 取loiter返回的每个结果
display('result {}:{}'.format(i, result))
main()
# out:
'''
Script starting
[23:10:39] loiter(0): doing nothing for 0s...
[23:10:39] loiter(0): done
[23:10:39] loiter(1): doing nothing for 1s...
[23:10:39] loiter(2): doing nothing for 2s...
[23:10:39] loiter(3): doing nothing for 3s...[23:10:39]
results: <generator object Executor.map.<locals>.result_iterator at 0x000001BC1D181A10>
[23:10:39] result 0:0
[23:10:40] loiter(1): done
[23:10:40] loiter(4): doing nothing for 4s...[23:10:40] result 1:10
[23:10:41] loiter(2): done
[23:10:41] result 2:20
[23:10:42] loiter(3): done
[23:10:42] result 3:30
[23:10:44] loiter(4): done
[23:10:44] result 4:40
Process finished with exit code 0
'''
标签:10,39,23,Python,并行,doing,result,loiter
From: https://www.cnblogs.com/czzz/p/16945983.html