Python中queue庫如何使用

今天就跟大家聊聊有關Python中queue庫如何使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

成都創(chuàng)新互聯(lián)公司為客戶提供專業(yè)的網(wǎng)站設計制作、成都網(wǎng)站制作、程序、域名、空間一條龍服務,提供基于WEB的系統(tǒng)開發(fā). 服務項目涵蓋了網(wǎng)頁設計、網(wǎng)站程序開發(fā)、WEB系統(tǒng)開發(fā)、微信二次開發(fā)、手機網(wǎng)站開發(fā)等網(wǎng)站方面業(yè)務。

queue模塊提供了適合多線程編程的先進先出的數(shù)據(jù)結(jié)構(gòu),可以用來在生產(chǎn)者和消費者線程之間安全的傳遞消息或者數(shù)據(jù);鎖是調(diào)用方處理,因此多線程可以安全、方便的使用同一隊列實現(xiàn)。

FIFO 隊列

Queue類,實現(xiàn)了最基礎的先進先出隊列,使用put方法,將元素添加到末尾,使用get方法將元素從另一邊刪除

def queue_fifo():
   q = queue.Queue()
   for i in range(5):
       q.put(i)

   while not q.empty():
       print (q.get(), end = ' ')
   print ()

LIFO 棧

與標準的FIFO隊列不同,LifoQueue實現(xiàn)了后進先出,這通常是棧;

def queue_lifo():
   q = queue.LifoQueue()
   for i in range(5):
       q.put(i)

   while not q.empty():
       print (q.get(), end = ' ')
   print ()

優(yōu)先級隊列

有時,隊列中元素的處理順序需要基于這些元素的特征,而不僅僅是添加到隊列中的順序。例如,財務部門的打印作業(yè)可能優(yōu)先于開發(fā)人員的代碼列表打印。PriorityQueue使用隊列內(nèi)容的排序順序來決定要檢索的元素。

class Job():
   def __init__(self, priority, description):
       self.priority = priority
       self.description = description
       print (description)
       return

   def __eq__(self, other):
       return self.priority == other.priority

   def __lt__(self, other):
       return self.priority < other.priority

def priority_queue():
   import threading
   print ('initial')
   q = queue.PriorityQueue()
   q.put(Job(5, 'Mid Job'))
   q.put(Job(10, 'Low Job'))
   q.put(Job(1, 'Imp Job'))

   def process_job(q):
       while True:
           next_job = q.get()
           print (next_job.description)
           q.task_done()
   workers = [
       threading.Thread(target=process_job, args=(q, )),
       threading.Thread(target=process_job, args=(q, )),
   ]
   print ('get')
   for w in workers:
       w.setDaemon(True)
       w.start()
   q.join()

Queue與多線程實戰(zhàn)

本節(jié)播放客戶端的源代碼演示Queue和多線程一起使用的場景。該程序讀取一個或多個RSS 摘要,將每一個摘要中五個最新事件放入Queue中等待下載,使用多線程并行處理下載。該框架實現(xiàn)演示了queue模塊的使用。

def podcast_client():
   ### 0. 初始化
   import threading
   num_fetch_threads = 2
   enclosure_queue = queue.Queue()
   feed_urls = [
       'http://talkpython.fm/episodes/rss',
   ]

   ### 1. 輔助函數(shù)打印信息
   def message(s):
       print ('{}: {}'.format(threading.current_thread().name, s))

   ### 2. 多線程目標函數(shù)函數(shù)
   def download_enclosures(q):
       import urllib
       message('looking for the next enclosure')
       url = q.get()
       filename = url.rpartition('/')[-1]
       message('downloading {}'.format(filename))
       response = urllib.request.urlopen(url)
       data = response.read()
       message('writing to {}'.format(filename))
       with open(filename, 'wb') as outfile:
           outfile.write(data)
       q.task_done()

   ### 3. 啟動多線程
   for i in range(num_fetch_threads):
       worker = threading.Thread(
           target = download_enclosures,
           args = (enclosure_queue, ),
           name = 'work-{}'.format(i),
       )
       worker.setDaemon(True)
       worker.start()

   ### 4. 隊列中添加URL
   import feedparser
   from urllib.parse import urlparse
   for url in feed_urls:
       response = feedparser.parse(url, agent='queue_module.py')
       for entry in response['entries'][:5]:
           for enclosure in entry.get('enclosures', []):
               parsed_url = urlparse(enclosure['url'])
               message('queuing {}'.format(
                   parsed_url.path.rpartition('/')[-1]))
               enclosure_queue.put(enclosure['url'])

   ### 5. 主線程
   message('*** main thread waiting')
   enclosure_queue.join()
   message('*** done')

首先,進行參數(shù)初始化,確定操作參數(shù):通常來自于用戶輸入。該示例使用硬編碼值,表示要獲取的線程數(shù)和URL列表,并創(chuàng)建用來打印信息的輔助函數(shù)message

在work線程中執(zhí)行download_enclosures方法,使用urllib處理下載。線程中定義了目標函數(shù)后,就可以啟動工作:download_enclosures方法中,語句url=q.get()執(zhí)行時,會阻塞并等待隊列返回內(nèi)容,這意味著在隊列沒有任何內(nèi)容之前啟動線程是安全的。

下一步是使用feedparser模塊(需要安裝)檢索摘要內(nèi)容,并將url插入到隊列中。一旦URL被添加到隊列中,線程就會將其讀取并開始下載,循環(huán)往隊列中添加元素,直到摘要消耗完,工作線程輪流講url出隊列下載。

看完上述內(nèi)容,你們對Python中queue庫如何使用有進一步的了解嗎?如果還想了解更多知識或者相關內(nèi)容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

本文名稱:Python中queue庫如何使用
本文來源:http://muchs.cn/article8/pideip.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、Google、品牌網(wǎng)站建設網(wǎng)站排名、外貿(mào)網(wǎng)站建設、搜索引擎優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營