线程队列,线程池和协程
線程的其他方法:
threading.current_thread() #當前線程對象
getName() # 獲取線程名
ident? # 獲取線程id
? ? ?threading.enumerate()? ?# 當前正在運行的線程對象的一個列表
threading.active_count()? # 當前正在運行的線程數量
import time from threading import Thread,current_threaddef f1(n):print(f"{n}號線程正在運行")print("子線程的名稱",current_thread().getName())if __name__ == '__main__':t = Thread(target=f1,args=(1,),name = '123')t.start()print("主線程的名稱", current_thread().getName())
?
線程隊列:(重點)
import queue
先進先出隊列:queue.Queue(3)
先進后出\后進先出隊列:queue.LifoQueue(3)?
優先級隊列:queue.priorityQueue(3)
? ? ? ? ? put的數據是一個元組,元組的第一個參數是優先級數字,數字越小優先級越高,越先被get到被取出來,第二個參數是put進去的值,如果說優先級相同,那么值別忘了應該是相同的數據類型,字典不行
import queue # q = queue.Queue(3) # q.put(1) # q.put(2) # print(q.qsize()) # try : # q.put_nowait(3) # except : # print('滿了') # print(q.full()) # # print(q.get()) # print(q.get()) # print(q.get())q = queue.PriorityQueue(3) q.put((2,'white')) q.put((1,'盧本偉')) q.put((2,'55開'))print(q.get()) print(q.get()) print(q.get())
?
線程池:
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
t?= ThreadPoolExecutor(4)? #默認的線程個數是cpu個數 * 5
p?= ProcessPoolExecutor(4)? #默認的進程個數是cpu個數
t.map(f1,可迭代的對象)? #異步執行
import time from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutordef f1(n):time.sleep(1)print(n)if __name__ == '__main__':t = ThreadPoolExecutor(5)t.map(f1,range(10))t.shutdown()print('主程序結束')
def f1(n1,n2):
print(n1,n2)
t.submit(f1,11,12)? #異步提交任務
res = t.submit(f1,11,12)?
res.result()? #和get方法一樣,如果沒有結果,會等待,阻塞程序
? ? shutdown()? # close+join,鎖定線程池,等待線程池中所有已經提交的任務全部執行完畢
import time from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutordef f1(n,m):time.sleep(1)print(n)return n+mif __name__ == '__main__':t = ThreadPoolExecutor(5)t_lis = []for i in range(10):ret = t.submit(f1,i,5)t_lis.append(ret)t.shutdown()for i in t_lis:print(i.result())print('主程序結束')
協程的概念:可以理解為微線程,在遇到io阻塞時,保存當前狀態并進行切換,且阻塞時間是并行的. 既節省時間,又提高效率.
import gevent? #導入模塊
gevent.sleep(1)? ?# 該方法的阻塞時間可以被識別并執行,如果是time.sleep()是不能識別,且不會節省時間的
g1 = gevent.spawn(f1)? ? # 異步提交f1和f2任務
g2 = gevent.spawn(f2)? ?# 異步提交f1和f2任務
gevent.joinall ( [g1,g2] )? ?# 等待執行完才繼續執行? ? ?相當于 g1.join() 和 g2.join()?
import geventdef f1():print('1號開啟游戲')gevent.sleep(2)print('1號吃雞了')def f2():print('2號開啟游戲')gevent.sleep(2)print('2號吃雞了')g1 = gevent.spawn(f1) #異步提交f1任務 g2 = gevent.spawn(f2) #異步提交f2任務g1.join() g2.join() # gevent.joinall([g1,g2])print("主程序結束")
轉載于:https://www.cnblogs.com/gyc-tzx/p/10268835.html
總結
以上是生活随笔為你收集整理的线程队列,线程池和协程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有源光缆AOC知识百科汇总
- 下一篇: 流程图绘制技巧及实战案例