日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

多线程中的应用之队列(queue)

發布時間:2025/5/22 69 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程中的应用之队列(queue) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

隊列queue 多應用在多線程中,對于多線程訪問共享變量時,隊列queue是線程安全的。
從queue隊列的實現來看,隊列使用了1個線程互斥鎖(pthread.Lock()),以及3個條件標量(pthread.condition()),
來保證了線程安全。

?self.mutex互斥鎖:任何獲取隊列的狀態(empty(),qsize()等),或者修改隊列的內容的操作(get,put等)都必須持有該互斥鎖。共有兩種操作require獲取鎖,release釋放鎖。同時該互斥鎖被三個共享變量同時享有,即操作conditiond時的require和release操作也就是操作了該互斥鎖。
?self.not_full條件變量:當隊列中有元素添加后,會通知notify其他等待添加元素的線程,喚醒等待require互斥鎖,或者有線程從隊列中取出一個元素后,通知其它線程喚醒以等待require互斥鎖。
?self.not empty條件變量:線程添加數據到隊列中后,會調用self.not_empty.notify()通知其它線程,喚醒等待require互斥鎖后,讀取隊列。
?self.all_tasks_done條件變量:消費者線程從隊列中get到任務后,任務處理完成,當所有的隊列中的任務處理完成后,會使調用queue.join()的線程返回,表示隊列中任務以處理完畢。

1,創建隊列對象
import Queue
q = Queue.Queue(maxsize = 5) #設置隊列長度為5,當有大于5個的數據put進隊列時,將阻塞(等待其它線程取走數據,將繼續執行)。
Queue.Queue類即是一個隊列的同步實現。隊列長度可為無限或者有限。可通過Queue的構造函數的可選參數maxsize來設定隊列長度。
如果maxsize小于1就表示隊列長度無限。

2,將一個值放入隊列
q.put(5) #put()方法在隊尾插入一個元素。
put()有兩個參數,第一個item為必需的,為插入項目的值;第二個block為可選參數,默認為1。
如果隊列當前已滿,且block為1,put()方法就使調用線程暫停,直到空出一個位置。如果block為0,put方法將引發Full異常。

3,將一個值從隊列取出
q.get() #get()方法從隊頭刪除并返回一個元素。
可選參數為block,默認為True。如果隊列為空且block為True,get()就使調用線程暫停,直至有元素可取。
如果隊列為空且block為False,隊列將引發Empty異常。

4,Queue模塊有三種隊列及構造函數:
(1),Python Queue模塊的FIFO隊列先進先出。 class queue.Queue(maxsize)
(2),LIFO類似于堆,即先進后出。 class queue.LifoQueue(maxsize)
(3),優先級隊列,優先級越低(數字越小)越先出來。 class queue.PriorityQueue(maxsize)
(4),雙端隊列(collections.deque)
例(優先級隊列):
格式:q.put([優先級,值])
q.put([2,"b"])
q.put([1,"a"])
q.put([3,"c"])
while True:
  data=q.get()
  print(data[1])
依次輸出:a,b,c

★常用方法(queue = Queue.Queue()):
queue.qsize() 返回隊列的大小
queue.empty() 如果隊列為空,返回True,反之False
queue.full() 如果隊列滿了,返回True,反之False
queue.full 與 maxsize 大小對應
queue.get(self, block=True, timeout=None) 獲取隊列中的一個元素,timeout等待時間
queue.get_nowait() 相當q.get(False);無阻塞的向隊列中get任務,當隊列為空時,不等待,而是直接拋出empty異常。
queue.put(self, item, block=True, timeout=None) 寫入隊列,timeout等待時間
queue.put_nowait(item) 相當q.put(item, False);無阻塞的向隊列中添加任務,當隊列為滿時,不等待,而是直接拋出full異常.
queue.task_done() 完成一項工作之后,q.task_done() 函數向任務已經完成的隊列發送一個信號
queue.join() 阻塞等待隊列中任務全部處理完畢,再執行別的操作。

★說明:
(1)queue.put(self, item, block=True, timeout=None)函數:
申請獲得互斥鎖,獲得后,如果隊列未滿,則向隊列中添加數據,并通知notify其它阻塞的某個線程,喚醒等待獲取require互斥鎖。
如果隊列已滿,則會wait等待。最后處理完成后釋放互斥鎖。其中還有阻塞block以及非阻塞,超時等。

(2)queue.get(self, block=True, timeout=None)函數:
從隊列中獲取任務,并且從隊列中移除此任務。首先嘗試獲取互斥鎖,獲取成功則隊列中get任務,如果此時隊列為空,則wait等待生產者線程添加數據。
get到任務后,會調用self.not_full.notify()通知生產者線程,隊列可以添加元素了。最后釋放互斥鎖。
  
(3)隊列的類定義:

1 class Queue: 2 """Create a queue object with a given maximum size. 3 4 If maxsize is <= 0, the queue size is infinite. 5 """ 6 def __init__(self, maxsize=0): 7 self.maxsize = maxsize 8 self._init(maxsize) 9 # mutex must be held whenever the queue is mutating. All methods 10 # that acquire mutex must release it before returning. mutex 11 # is shared between the three conditions, so acquiring and 12 # releasing the conditions also acquires and releases mutex. 13 self.mutex = _threading.Lock() 14 # Notify not_empty whenever an item is added to the queue; a 15 # thread waiting to get is notified then. 16 self.not_empty = _threading.Condition(self.mutex) 17 # Notify not_full whenever an item is removed from the queue; 18 # a thread waiting to put is notified then. 19 self.not_full = _threading.Condition(self.mutex) 20 # Notify all_tasks_done whenever the number of unfinished tasks 21 # drops to zero; thread waiting to join() is notified to resume 22 self.all_tasks_done = _threading.Condition(self.mutex) 23 self.unfinished_tasks = 0 24 25 def task_done(self): 26 """Indicate that a formerly enqueued task is complete. 27 28 Used by Queue consumer threads. For each get() used to fetch a task, 29 a subsequent call to task_done() tells the queue that the processing 30 on the task is complete. 31 32 If a join() is currently blocking, it will resume when all items 33 have been processed (meaning that a task_done() call was received 34 for every item that had been put() into the queue). 35 36 Raises a ValueError if called more times than there were items 37 placed in the queue. 38 """ 39 self.all_tasks_done.acquire() 40 try: 41 unfinished = self.unfinished_tasks - 1 42 if unfinished <= 0: 43 if unfinished < 0: 44 raise ValueError('task_done() called too many times') 45 self.all_tasks_done.notify_all() 46 self.unfinished_tasks = unfinished 47 finally: 48 self.all_tasks_done.release() 49 50 def join(self): 51 """Blocks until all items in the Queue have been gotten and processed. 52 53 The count of unfinished tasks goes up whenever an item is added to the 54 queue. The count goes down whenever a consumer thread calls task_done() 55 to indicate the item was retrieved and all work on it is complete. 56 57 When the count of unfinished tasks drops to zero, join() unblocks. 58 """ 59 self.all_tasks_done.acquire() 60 try: 61 while self.unfinished_tasks: 62 self.all_tasks_done.wait() 63 finally: 64 self.all_tasks_done.release() 65 66 def qsize(self): 67 """Return the approximate size of the queue (not reliable!).""" 68 self.mutex.acquire() 69 n = self._qsize() 70 self.mutex.release() 71 return n 72 73 def empty(self): 74 """Return True if the queue is empty, False otherwise (not reliable!).""" 75 self.mutex.acquire() 76 n = not self._qsize() 77 self.mutex.release() 78 return n 79 80 def full(self): 81 """Return True if the queue is full, False otherwise (not reliable!).""" 82 self.mutex.acquire() 83 n = 0 < self.maxsize == self._qsize() 84 self.mutex.release() 85 return n 86 87 def put(self, item, block=True, timeout=None): 88 """Put an item into the queue. 89 90 If optional args 'block' is true and 'timeout' is None (the default), 91 block if necessary until a free slot is available. If 'timeout' is 92 a non-negative number, it blocks at most 'timeout' seconds and raises 93 the Full exception if no free slot was available within that time. 94 Otherwise ('block' is false), put an item on the queue if a free slot 95 is immediately available, else raise the Full exception ('timeout' 96 is ignored in that case). 97 """ 98 self.not_full.acquire() 99 try: 100 if self.maxsize > 0: 101 if not block: 102 if self._qsize() == self.maxsize: 103 raise Full 104 elif timeout is None: 105 while self._qsize() == self.maxsize: 106 self.not_full.wait() 107 elif timeout < 0: 108 raise ValueError("'timeout' must be a non-negative number") 109 else: 110 endtime = _time() + timeout 111 while self._qsize() == self.maxsize: 112 remaining = endtime - _time() 113 if remaining <= 0.0: 114 raise Full 115 self.not_full.wait(remaining) 116 self._put(item) 117 self.unfinished_tasks += 1 118 self.not_empty.notify() 119 finally: 120 self.not_full.release() 121 122 def put_nowait(self, item): 123 """Put an item into the queue without blocking. 124 125 Only enqueue the item if a free slot is immediately available. 126 Otherwise raise the Full exception. 127 """ 128 return self.put(item, False) 129 130 def get(self, block=True, timeout=None): 131 """Remove and return an item from the queue. 132 133 If optional args 'block' is true and 'timeout' is None (the default), 134 block if necessary until an item is available. If 'timeout' is 135 a non-negative number, it blocks at most 'timeout' seconds and raises 136 the Empty exception if no item was available within that time. 137 Otherwise ('block' is false), return an item if one is immediately 138 available, else raise the Empty exception ('timeout' is ignored 139 in that case). 140 """ 141 self.not_empty.acquire() 142 try: 143 if not block: 144 if not self._qsize(): 145 raise Empty 146 elif timeout is None: 147 while not self._qsize(): 148 self.not_empty.wait() 149 elif timeout < 0: 150 raise ValueError("'timeout' must be a non-negative number") 151 else: 152 endtime = _time() + timeout 153 while not self._qsize(): 154 remaining = endtime - _time() 155 if remaining <= 0.0: 156 raise Empty 157 self.not_empty.wait(remaining) 158 item = self._get() 159 self.not_full.notify() 160 return item 161 finally: 162 self.not_empty.release() 163 164 def get_nowait(self): 165 """Remove and return an item from the queue without blocking. 166 167 Only get an item if one is immediately available. Otherwise 168 raise the Empty exception. 169 """ 170 return self.get(False) 171 172 # Override these methods to implement other queue organizations 173 # (e.g. stack or priority queue). 174 # These will only be called with appropriate locks held 175 176 # Initialize the queue representation 177 def _init(self, maxsize): 178 self.queue = deque() 179 180 def _qsize(self, len=len): 181 return len(self.queue) 182 183 # Put a new item in the queue 184 def _put(self, item): 185 self.queue.append(item) 186 187 # Get an item from the queue 188 def _get(self): 189 return self.queue.popleft() View Code

?

轉載于:https://www.cnblogs.com/mountain2011/p/11343254.html

總結

以上是生活随笔為你收集整理的多线程中的应用之队列(queue)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。