一、线程队列
队列特性:取一个值少一个,只能取一次,没有值的时候会阻塞,队列满了,也会阻塞
queue队列 :使用import queue,用法与进程Queue一样
queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
三种类型:
(1)先进先出 (fifo) q=queue.Queue
(2)#后进先出,先进后出 (Lifo) q=queue.LifoQueue
优先队列 (Priority) q=queue.PriorityQueue(5)
二、python 标准模块--concurrent.futures
到这里就差我们的线程池没有讲了,我们用一个新的模块给大家讲,早期的时候我们没有线程池,现在python提供了一个新的标准或者说内置的模块,这个模块里面提供了新的线程池和进程池,之前我们说的进程池是在multiprocessing里面的,现在这个在这个新的模块里面,他俩用法上是一样的。
为什么要将进程池和线程池放到一起呢,是为了统一使用方式,使用threadPollExecutor和ProcessPoolExecutor的方式一样,而且只要通过这个concurrent.futures导入就可以直接用他们两个了.
模块方法解析
concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor: 进程池,提供异步调用 Both implement the same interface, which is defined by the abstract Executor class. #2 基本方法 #submit(fn, *args, **kwargs) 异步提交任务 #map(func, *iterables, timeout=None, chunksize=1) 取代for循环submit的操作 #shutdown(wait=True) 相当于进程池的pool.close()+pool.join()操作 wait=True,等待池内所有任务执行完毕回收完资源后才继续 wait=False,立即返回,并不会等待池内的任务执行完毕 但不管wait参数为何值,整个程序都会等到所有任务执行完毕 submit和map必须在shutdown之前 #result(timeout=None) 取得结果 #add_done_callback(fn) 回调函数
三、concurrent.futures模块的应用:线程池、进程池
submit()和shutdown()的应用
import time from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor def fun(n): time.sleep(1) return n*n if __name__ == '__main__': t_p=ThreadPoolExecutor(max_workers=4) #创建线程池,池子中只有四个线程可以同时运行 #从concurrent.futures引入ThreadPoolExecutor,ProcessPoolExecutor,可以让进程与线程之间的代码通用,只需将 # ThreadPoolExecutor与ProcessPoolExecutor互换 # t_p=ProcessPoolExecutor(max_workers=4)#创建进程池,池子中只有四个进程可以同时运行, res_lst=[] for i in range(1,11): res=t_p.submit(fun,i) #submit(func,*args) 创建线程,返回值是线程对象 # print(res) #获取线程对象,并没有执行线程的函数 <Future at 0x1df505f2390 state=pending> # print(res.result()) #for 循环内部的result获取对象结果,会阻塞程序运行,直至拿到该线程的结果 res_lst.append(res) #按照先后循序存放线程结果 [res1,res2...res10] t_p.shutdown() #相当于 pool.close() +pool.join() 确保池子里面的线程全部执行完毕,再进行主程序代码 print("主程序结束") #从结果对象列表中取数据 for res1 in res_lst: print(res1.result())