线程池–concurrent
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/28 15:54
# @Author : InsaneLoafer
# @File : thread_pool.py
import os
import time
import threading
from concurrent.futures import ThreadPoolExecutor
lock = threading.Lock() # 定义全局锁
def work(i):
# lock.acquire()
print(i, os.getpid())
time.sleep(1)
# lock.release()
return 'result: %s' % i
if __name__ == '__main__':
print(os.getpid())
t = ThreadPoolExecutor(2)
result = []
for i in range(20):
t_result = t.submit(work, (i,))
result.append(t_result)
for res in result:
print(res.result())
34320
(0,) 34320
(1,) 34320
(2,)(3,)result: 0
34320
result: 134320
(4,)(5,)result: 2
34320result: 3
34320
(6,) 34320
(7,) 34320result: 4
result: 5
(8,)(9,) result: 634320
34320result: 7
(10,)(11,) 34320result: 834320
result: 9
(12,)(13,)result: 10 34320
34320
result: 11
(14,)(15,)result: 12
34320result: 13
34320
(16,)(17,) result: 14
34320result: 1534320
(18,)(19,)result: 16 34320
result: 17
34320
result: 18
result: 19
Process finished with exit code 0