场景:进程中的线程在执行完成后就会销毁,下次执行任务时再次创建;线程的频繁创建涉及和操作系统的交互,有一定的时间和资源成本,线程池应用而生;
Python 官方文档:https://docs.python.org/zh-cn/3/library/concurrent.futures.html?
import time
from datetime import datetime
import threading
list = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk"]
lock = threading.Lock()
def deleteElement():
global list
while True:
lock.acquire()
if not list:
lock.release()
break
else:
ele = list.pop()
print("{}-->{}-->{}".format(threading.current_thread().name,datetime.now(), ele))
lock.release()
time.sleep(1)
if __name__ == "__main__":
task_a = threading.Thread(target=deleteElement, name="task-A")
task_b = threading.Thread(target=deleteElement, name="task-B")
task_a.start()
task_b.start()
task_a.join()
task_b.join()
print("mainThread现场执行完成")
注意:该代码中当列表为空退出时,需要同时释放 lock,否则将陷入死锁状态;
import time
from datetime import datetime
import threading
from concurrent.futures import ThreadPoolExecutor
list = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk"]
def outputList(ele):
print("{}-->{}-->{}".format(threading.current_thread().name, datetime.now(), ele))
time.sleep(1)
if __name__ == "__main__":
pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix='task')
for x in list:
future = pool.submit(outputList, x)
future.result()
print("mainThread现场执行完成")
说明:此处的 future.result() 阻塞式的获取结果,可以确保主线程的内容最后执行;
from concurrent.futures import as_completed
for o in as_completed(future_list):
o.result()
实现非阻塞式的结果获取
================================ over ========================================