日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時(shí)間:2025/5/22 编程问答 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程中的应用之队列(queue) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

隊(duì)列queue 多應(yīng)用在多線程中,對(duì)于多線程訪問共享變量時(shí),隊(duì)列queue是線程安全的。
從queue隊(duì)列的實(shí)現(xiàn)來看,隊(duì)列使用了1個(gè)線程互斥鎖(pthread.Lock()),以及3個(gè)條件標(biāo)量(pthread.condition()),
來保證了線程安全。

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

1,創(chuàng)建隊(duì)列對(duì)象
import Queue
q = Queue.Queue(maxsize = 5) #設(shè)置隊(duì)列長(zhǎng)度為5,當(dāng)有大于5個(gè)的數(shù)據(jù)put進(jìn)隊(duì)列時(shí),將阻塞(等待其它線程取走數(shù)據(jù),將繼續(xù)執(zhí)行)。
Queue.Queue類即是一個(gè)隊(duì)列的同步實(shí)現(xiàn)。隊(duì)列長(zhǎng)度可為無限或者有限。可通過Queue的構(gòu)造函數(shù)的可選參數(shù)maxsize來設(shè)定隊(duì)列長(zhǎng)度。
如果maxsize小于1就表示隊(duì)列長(zhǎng)度無限。

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

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

4,Queue模塊有三種隊(duì)列及構(gòu)造函數(shù):
(1),Python Queue模塊的FIFO隊(duì)列先進(jìn)先出。 class queue.Queue(maxsize)
(2),LIFO類似于堆,即先進(jìn)后出。 class queue.LifoQueue(maxsize)
(3),優(yōu)先級(jí)隊(duì)列,優(yōu)先級(jí)越低(數(shù)字越小)越先出來。 class queue.PriorityQueue(maxsize)
(4),雙端隊(duì)列(collections.deque)
例(優(yōu)先級(jí)隊(duì)列):
格式:q.put([優(yōu)先級(jí),值])
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() 返回隊(duì)列的大小
queue.empty() 如果隊(duì)列為空,返回True,反之False
queue.full() 如果隊(duì)列滿了,返回True,反之False
queue.full 與 maxsize 大小對(duì)應(yīng)
queue.get(self, block=True, timeout=None) 獲取隊(duì)列中的一個(gè)元素,timeout等待時(shí)間
queue.get_nowait() 相當(dāng)q.get(False);無阻塞的向隊(duì)列中g(shù)et任務(wù),當(dāng)隊(duì)列為空時(shí),不等待,而是直接拋出empty異常。
queue.put(self, item, block=True, timeout=None) 寫入隊(duì)列,timeout等待時(shí)間
queue.put_nowait(item) 相當(dāng)q.put(item, False);無阻塞的向隊(duì)列中添加任務(wù),當(dāng)隊(duì)列為滿時(shí),不等待,而是直接拋出full異常.
queue.task_done() 完成一項(xiàng)工作之后,q.task_done() 函數(shù)向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個(gè)信號(hào)
queue.join() 阻塞等待隊(duì)列中任務(wù)全部處理完畢,再執(zhí)行別的操作。

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

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

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

?

轉(zhuǎn)載于:https://www.cnblogs.com/mountain2011/p/11343254.html

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。