您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關怎樣理解Python線程池,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
總結一下自己總結的對Python線程池經驗之談,對于那些沒有接觸學習過編程語言或者多開發語言略懂的用戶而言,Python語言是絕對的選擇之一,并建議初學的程序員先從Python開始學習編程。
import Queue, threading, sys from threading import Thread import time,urllib # working thread class Worker(Thread): worker_count = 0 def __init__( self, workQueue, resultQueue, timeout = 0, **kwds): Thread.__init__( self, **kwds ) self.id = Worker.worker_count Worker.worker_count += 1 self.setDaemon( True ) self.workQueue = workQueue self.resultQueue = resultQueue self.timeout = timeout self.start( ) def run( self ): ''' the get-some-work, do-some-work main loop of worker threads ''' while True: try: callable, args, kwds = self.workQueue.get(timeout=self.timeout) res = callable(*args, **kwds) print "worker[%2d]: %s" % (self.id, str(res) ) self.resultQueue.put( res ) except Queue.Empty: break except : print 'worker[%2d]' % self.id, sys.exc_info()[:2] class WorkerManager: def __init__( self, num_of_workers=10, timeout = 1): self.workQueue = Queue.Queue() self.resultQueue = Queue.Queue() self.workers = [] self.timeout = timeout self._recruitThreads( num_of_workers ) def _recruitThreads( self, num_of_workers ): for i in range( num_of_workers ): worker = Worker( self.workQueue, self.resultQueue, self.timeout ) self.workers.append(worker) def wait_for_complete( self): # ...then, wait for each of them to terminate: while len(self.workers): worker = self.workers.pop() worker.join( ) if worker.isAlive() and not self.workQueue.empty(): self.workers.append( worker ) print "All jobs are are completed." def add_job( self, callable, *args, **kwds ): self.workQueue.put( (callable, args, kwds) ) def get_result( self, *args, **kwds ): return self.resultQueue.get( *args, **kwds )
Worker類是一個Python線程池,不斷地從workQueue隊列中獲取需要執行的任務,執行之,并將結果寫入到resultQueue中。這里的workQueue和resultQueue都是現成安全的,其內部對各個線程的操作做了互斥。當從workQueue中獲取任務超時,則線程結束。
WorkerManager負責初始化Python線程池,提供將任務加入隊列和獲取結果的接口,并能等待所有任務完成。一個典型的測試例子如下,它用10個線程去下載一個固定頁面的內容,實際應用時應該是執行不同的任務。
def test_job(id, sleep = 0.001 ): try: urllib.urlopen('[url]https://www.gmail.com/[/url]').read() except: print '[%4d]' % id, sys.exc_info()[:2] return id def test(): import socket socket.setdefaulttimeout(10) print 'start testing' wm = WorkerManager(10) for i in range(500): wm.add_job( test_job, i, i*0.001 ) wm.wait_for_complete() print 'end testing'
以上就是怎樣理解Python線程池,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。