一个多线程、多进程的脚本
2020-07-20 本文已影响0人
lvyz0207
IO 密集多尽量用多线程,
CPU 密集尽量用多进程
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time
def func(args):
print(f'call func {args}')
if __name__ == "__main__":
seed = ['a', 'b', 'c', 'd']
# 多线程
with ThreadPoolExecutor(3) as executor:
executor.submit(func, seed) # call func ['a', 'b', 'c', 'd']
time.sleep(1)
# 多进程
start = time.time()
with ProcessPoolExecutor() as process: # 不指定进程数,默认为系统的核心数
future_tasks = [process.submit(func, seed)]
print(time.time() - start)
# with ThreadPoolExecutor(3) as executor2:
# executor2.map(func, seed) # 列表映射,传入四次
# time.sleep(1)
# with ThreadPoolExecutor(max_workers=1) as executor:
# future = executor.submit(pow, 2, 3)
# print(future.result())
![](https://img.haomeiwen.com/i12208052/874dde3933f6dca1.jpg)