python3 使用线程池、进程池完成多线程、多进程任务

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor #线程池,进程池
import threading,time

def test(arg):
    print(arg,threading.current_thread().name)
    time.sleep(1)

if __name__ == "__main__":
    thread_pool = ThreadPoolExecutor(5) #定义5个线程执行此任务
    process_pool = ProcessPoolExecutor(5) #定义5个进程
    for i in range(20):
        thread_pool.submit(test,i)
        #process_pool.submit(test,i)

执行结果,可以看到任务按计划完成,所有线程顺序基本随机:

C:\Python37\python.exe C:/Users/mayn/PycharmProjects/test11/线程池进程池.py
0 ThreadPoolExecutor-0_0
1 ThreadPoolExecutor-0_1
2 ThreadPoolExecutor-0_2
3 ThreadPoolExecutor-0_3
4 ThreadPoolExecutor-0_4
5 ThreadPoolExecutor-0_0
6 ThreadPoolExecutor-0_3
7 ThreadPoolExecutor-0_4
89 ThreadPoolExecutor-0_2
 ThreadPoolExecutor-0_1
10 ThreadPoolExecutor-0_0
11 ThreadPoolExecutor-0_4
12 ThreadPoolExecutor-0_1
13 ThreadPoolExecutor-0_3
14 ThreadPoolExecutor-0_2
15 ThreadPoolExecutor-0_0
16 ThreadPoolExecutor-0_2
17 ThreadPoolExecutor-0_4
18 ThreadPoolExecutor-0_1
19 ThreadPoolExecutor-0_3

 

你可能感兴趣的:(Python)