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