python3?queue多線程通信
queue分類
python3 queue分三類:
- 先進先出隊列
- 后進先出的棧
- 優(yōu)先級隊列
他們的導入方式分別是:
from queue import Queue from queue import LifoQueue from queue import
具體方法見下面引用說明。
例子一、生產消費模式
Queue 對象已經包含了必要的鎖,所以你可以通過它在多個線程間多安全地共享數(shù)據(jù)。 當使用隊列時,協(xié)調生產者和消費者的關閉問題可能會有一些麻煩。一個通用的解決方法是在隊列中放置一個特殊的值,當消費者讀到這個值的時候,終止執(zhí)行。
例如:
from queue import Queue
from threading import Thread
# 用來表示終止的特殊對象
_sentinel = object()
# A thread that produces data
def producer(out_q):
for i in range(10):
print("生產")
out_q.put(i)
out_q.put(_sentinel)
# A thread that consumes data
def consumer(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()結果:

本例中有一個特殊的地方:消費者在讀到這個特殊值之后立即又把它放回到隊列中,將之傳遞下去。這樣,所有監(jiān)聽這個隊列的消費者線程就可以全部關閉了。 盡管隊列是最常見的線程間通信機制,但是仍然可以自己通過創(chuàng)建自己的數(shù)據(jù)結構并添加所需的鎖和同步機制來實現(xiàn)線程間通信。最常見的方法是使用 Condition變量來包裝你的數(shù)據(jù)結構。下邊這個例子演示了如何創(chuàng)建一個線程安全的優(yōu)先級隊列。
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: heapq.heappush(self._queue, (-priority, self._count, item)) self._count += 1 self._cv.notify() def get(self): with self._cv: while len(self._queue) == 0: self._cv.wait() return heapq.heappop(self._queue)[-1]
例子二、task_done和join
使用隊列來進行線程間通信是一個單向、不確定的過程。通常情況下,你沒有辦法知道接收數(shù)據(jù)的線程是什么時候接收到的數(shù)據(jù)并開始工作的。不過隊列對象提供一些基本完成的特性,比如下邊這個例子中的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
def run(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
def run(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()結果:

例子三、多線程里用queue
設置倆隊列,一個是要做的任務隊列todo_queue,一個是已經完成的隊列done_queue。
每次執(zhí)行線程,先從todo_queue隊列里取出一個值,然后執(zhí)行完,放入done_queue隊列。
如果todo_queue為空,就退出。
import logging
import logging.handlers
import threading
import queue
log_mgr = None
todo_queue = queue.Queue()
done_queue = queue.Queue()
class LogMgr:
def __init__(self, logpath):
self.LOG = logging.getLogger('log')
loghd = logging.handlers.RotatingFileHandler(logpath, "a", 0, 1)
fmt = logging.Formatter("%(asctime)s %(threadName)-10s %(message)s", "%Y-%m-%d %H:%M:%S")
loghd.setFormatter(fmt)
self.LOG.addHandler(loghd)
self.LOG.setLevel(logging.INFO)
def info(self, msg):
if self.LOG is not None:
self.LOG.info(msg)
class Worker(threading.Thread):
global log_mgr
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
while True:
try:
task = todo_queue.get(False)
if task:
log_mgr.info("HANDLE_TASK: %s" % task)
done_queue.put(1)
except queue.Empty:
break
return
def main():
global log_mgr
log_mgr = LogMgr("mylog")
for i in range(30):
todo_queue.put("data"+str(i))
workers = []
for i in range(3):
w = Worker("worker"+str(i))
workers.append(w)
for i in range(3):
workers[i].start()
for i in range(3):
workers[i].join()
total_num = done_queue.qsize()
log_mgr.info("TOTAL_HANDLE_TASK: %d" % total_num)
exit(0)
if __name__ == '__main__':
main()輸出日志文件結果:

到此這篇關于python3 queue多線程通信的文章就介紹到這了,更多相關python queue多線程通信內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在Python中使用defaultdict初始化字典以及應用方法
今天小編就為大家分享一篇在Python中使用defaultdict初始化字典以及應用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
小議Python中自定義函數(shù)的可變參數(shù)的使用及注意點
Python函數(shù)的默認值參數(shù)只會在函數(shù)定義處被解析一次,以后再使用時這個默認值還是一樣,這在與可變參數(shù)共同使用時便會產生困惑,下面就來小議Python中自定義函數(shù)的可變參數(shù)的使用及注意點2016-06-06
windows下python安裝paramiko模塊和pycrypto模塊(簡單三步)
這篇文章主要給大家介紹了通過簡單的三個步驟在windows下python中安裝paramiko模塊和pycrypto模塊的相關資料,文中安裝的步驟,簡單而且又易于大家理解,需要的朋友們下面跟著小編一起來學習學習吧。2017-07-07

