有了python執行緒的基礎概念python多執行緒–(1)之基本概念
在python中應用執行緒,threading模組的了解python多執行緒–(2)之threading模組
以及多執行緒程式設計中最重要的一方面–同步python多執行緒–(3)同步
具體來說,實現的方式也是和很簡單的,可以理解為建立了乙個公共可以訪問的佇列,執行緒都可以訪問它。具體的queue模組有的一些屬性如下:
queue模組中的類:
異常:queue物件方法:
之前的訊號量例子,改用queue來進行資源的共享
from random import randint
from queue import queue
from time import sleep
from test_8_25.mythread import mythread
defwrite_queue
(queue):
# 新增佇列中元素行為
print('producing object for queue...', queue.put('***', 1))
print('size now', queue.qsize())
defread_queue
(queue):
#消耗佇列中元素行為
queue.get(1)
print('consumed object from queue...')
print('size now', queue.qsize())
defwriter
(queue, loops):
#隨機向佇列中新增隨機個數的元素
for i in range(loops):
write_queue(queue)
sleep(randint(1, 3))
defreader
(queue, loops):
# 隨機消耗佇列中隨機個數的元素
for i in range(loops):
read_queue(queue)
sleep(randint(2,5))#等待時間比writer常,盡量避免佇列在消耗時為空
funcs = [writer, reader]
nfuncs = range(len(funcs))
defmain
(): nloops =randint(2,5)#隨機產生執行緒數
q = queue(32) #獲得共享佇列
threads = #執行緒列表
for i in nfuncs: #生成所有的執行緒列表
t = mythread(funcs[i], (q, nloops), funcs[i].__name__)
for i in nfuncs:
threads[i].start() #開啟所有的執行緒
for i in nfuncs:
threads[i].join() #這裡需要將執行緒掛起,否則主線程會執行緒結束前列印「all done」
# 或者你也可以使用atexit()來限制在主線程退出時在列印
print("all done.")
if __name__ == '__main__':
main()
結果例項(結果隨機不盡相同):
starting writer at: sat aug 26
19:27:42
2017
producing object for queue
...none
size now 1
starting reader at: sat aug 26
19:27:42
2017
consumed object from queue
...size now 0
producing object for queue
...none
size now 1
producing object for queue
...none
size now 2
consumed object from queue
...size now 1
consumed object from queue
...size now 0
producing object for queue
...none
size now 1
consumed object from queue
...size now 0
writer finished at: sat aug 26
19:27:53
2017
reader finished at: sat aug 26
19:27:53
2017
all done.
python 多執行緒 queue
python的queue設計的是執行緒安全的,所以大傢伙放心用吧!python多執行緒的一種簡單的實現如下 usr bin env python coding utf 8 import threading import time deffun argv print in argv time.slee...
多執行緒queue
一 class queue.queue maxsize 0 佇列 先進先出 import queue q queue.queue q.put first q.put second q.put third print q.get print q.get print q.get 結果 先進先出 firs...
python多執行緒爬蟲學習 Queue
queue是python多執行緒安全的佇列實現,封裝了資料結構中的佇列,保證了執行緒之間使用佇列同步資料不會出錯。也就是說使用queue就不用使用鎖去同步資料。queue預設構造的大小是無限的,也可以在初始化時指定佇列大小 queue q 10 queue的使用函式 get 獲取佇列頭部元素,並且把...