python3 佇列queue的用法

2021-10-08 22:34:50 字數 3409 閱讀 3834

python3 queue分三類:

先進先出佇列

後進先出的棧

優先順序佇列

他們的匯入方式分別是:

from queue import queue

from queue import lifoqueue

from queue import priorityqueue

queue 物件已經包含了必要的鎖,所以你可以通過它在多個執行緒間多安全地共享資料。 當使用佇列時,協調生產者和消費者的關閉問題可能會有一些麻煩。乙個通用的解決方法是在佇列中放置乙個特殊的值,當消費者讀到這個值的時候,終止執行。例如:

from queue import queue

from threading import thread

# 用來表示終止的特殊物件

_sentinel =

object()

# a thread that produces data

defproducer

(out_q)

:for i in

range(10

):print

("生產"

) out_q.put(i)

out_q.put(_sentinel)

# a thread that consumes data

defconsumer

(in_q)

:while

true

: data = in_q.get(

)if data is _sentinel:

in_q.put(_sentinel)

break

else

:print

("消費"

, data)

# create the shared queue and launch both threads

q = queue(

)t1 = thread(target=consumer, args=

(q,)

)t2 = thread(target=producer, args=

(q,)

)t1.start(

)t2.start(

)

本例中有乙個特殊的地方:消費者在讀到這個特殊值之後立即又把它放回到佇列中,將之傳遞下去。這樣,所有監聽這個佇列的消費者執行緒就可以全部關閉了。 儘管佇列是最常見的執行緒間通訊機制,但是仍然可以自己通過建立自己的資料結構並新增所需的鎖和同步機制來實現執行緒間通訊。最常見的方法是使用 condition 變數來包裝你的資料結構。下邊這個例子演示了如何建立乙個執行緒安全的優先順序佇列。

import heapq

import threading

class

priorityqueue

:def

__init__

(self)

: self._queue =

self._count =

0 self._cv = threading.condition(

)def

put(self, item, priority)

:with self._cv:

(-priority, self._count, item)

) self._count +=

1 self._cv.notify(

)def

get(self)

:with self._cv:

while

len(self._queue)==0

: self._cv.wait()[

-1]

使用佇列來進行執行緒間通訊是乙個單向、不確定的過程。通常情況下,你沒有辦法知道接收資料的執行緒是什麼時候接收到的資料並開始工作的。不過佇列物件提供一些基本完成的特性,比如下邊這個例子中的 task_done() 和 join()

from queue import queue

from threading import thread

class

producer

(thread)

:def

__init__

(self, q)

:super()

.__init__(

) self.count =

5 self.q = q

defrun(self)

:while self.count >0:

print

("生產"

)if self.count ==1:

self.count -=

1 self.q.put(2)

else

: self.count -=

1 self.q.put(1)

class

consumer

(thread)

:def

__init__

(self, q)

:super()

.__init__(

) self.q = q

defrun(self)

:while

true

:print

("消費"

) data = self.q.get(

)if data ==2:

print

("stop because data="

, data)

# 任務完成,從佇列中清除乙個元素

self.q.task_done(

)break

else

:print

("data is good,data="

, data)

# 任務完成,從佇列中清除乙個元素

self.q.task_done(

)def

main()

: q = queue(

) p = producer(q)

c = consumer(q)

p.setdaemon(

true

) c.setdaemon(

true

) p.start(

) c.start(

)# 等待佇列清空

q.join(

)print

("queue is complete"

)if __name__ ==

'__main__'

: main(

)

python3 佇列的簡單用法Queue

佇列的簡單使用,佇列先進先出 import queue 不能用於多程序之間的通訊,可以用於多執行緒間的通訊 from multiprocessing import queue 可以用於程序之間的資料共享 q queue 3 建立乙個佇列物件,佇列長度為3 q.put 1 q.put 2 q.put ...

python3佇列使用

python3直接import queue 會報錯,要改成import queue from queue import queue maxsize 1 from queue import queue 執行緒佇列通訊使用 這個是普通的佇列模式,類似於普通列表,先進先出模式,get方法會阻塞請求,直到有...

python筆記29 佇列Queue

python的queue模組提供一種適用於多執行緒程式設計的fifo實現。它可用於在生產者 producer 和消費者 consumer 之間執行緒安全 thread safe 地傳遞訊息或其它資料,因此多個執行緒可以共用同乙個queue例項。queue的大小 元素的個數 可用來限制記憶體的使用。p...