用python實(shí)現(xiàn)的線程池實(shí)例代碼
python3標(biāo)準(zhǔn)庫(kù)里自帶線程池ThreadPoolExecutor和進(jìn)程池ProcessPoolExecutor。
如果你用的是python2,那可以下載一個(gè)模塊,叫threadpool,這是線程池。對(duì)于進(jìn)程池可以使用python自帶的multiprocessing.Pool。
當(dāng)然也可以自己寫一個(gè)threadpool。
# coding:utf-8
import Queue
import threading
import sys
import time
import math
class WorkThread(threading.Thread):
def __init__(self, task_queue):
threading.Thread.__init__(self)
self.setDaemon(True)
self.task_queue = task_queue
self.start()
self.idle = True
def run(self):
sleep_time = 0.01 # 第1次無(wú)任務(wù)可做時(shí)休息10毫秒
multiply = 0
while True:
try:
# 從隊(duì)列中取一個(gè)任務(wù)
func, args, kwargs = self.task_queue.get(block=False)
self.idle = False
multiply = 0
# 執(zhí)行之
func(*args, **kwargs)
except Queue.Empty:
time.sleep(sleep_time * math.pow(2, multiply))
self.idle = True
multiply += 1
continue
except:
print sys.exc_info()
raise
class ThreadPool:
def __init__(self, thread_num=10, max_queue_len=1000):
self.max_queue_len = max_queue_len
self.task_queue = Queue.Queue(max_queue_len) # 任務(wù)等待隊(duì)列
self.threads = []
self.__create_pool(thread_num)
def __create_pool(self, thread_num):
for i in xrange(thread_num):
thread = WorkThread(self.task_queue)
self.threads.append(thread)
def add_task(self, func, *args, **kwargs):
'''添加一個(gè)任務(wù),返回任務(wù)等待隊(duì)列的長(zhǎng)度
調(diào)用該方法前最后先調(diào)用isSafe()判斷一下等待的任務(wù)是不是很多,以防止提交的任務(wù)被拒絕
'''
try:
self.task_queue.put((func, args, kwargs))
except Queue.Full:
raise # 隊(duì)列已滿時(shí)直接拋出異常,不給執(zhí)行
return self.task_queue.qsize()
def isSafe(self):
'''等待的任務(wù)數(shù)量離警界線還比較遠(yuǎn)
'''
return self.task_queue.qsize() < 0.9 * self.max_queue_len
def wait_for_complete(self):
'''等待提交到線程池的所有任務(wù)都執(zhí)行完畢
'''
#首先任務(wù)等待隊(duì)列要變成空
while not self.task_queue.empty():
time.sleep(1)
# 其次,所以計(jì)算線程要變成idle狀態(tài)
while True:
all_idle = True
for th in self.threads:
if not th.idle:
all_idle = False
break
if all_idle:
break
else:
time.sleep(1)
if __name__ == '__main__':
def foo(a, b):
print a + b
time.sleep(0.01)
thread_pool = ThreadPool(10, 100)
'''在Windows上測(cè)試不通過(guò),Windows上Queue.Queue不是線程安全的'''
size = 0
for i in xrange(10000):
try:
size = thread_pool.add_task(foo, i, 2 * i)
except Queue.Full:
print 'queue full, queue size is ', size
time.sleep(2)
總結(jié)
以上就是本文關(guān)于用python實(shí)現(xiàn)的線程池實(shí)例代碼的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
- python線程池threadpool使用篇
- Python自定義線程池實(shí)現(xiàn)方法分析
- 淺談python 線程池threadpool之實(shí)現(xiàn)
- python線程池(threadpool)模塊使用筆記詳解
- php與python實(shí)現(xiàn)的線程池多線程爬蟲(chóng)功能示例
- python實(shí)現(xiàn)線程池的方法
- Python實(shí)現(xiàn)線程池代碼分享
- 用Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的線程池
- python線程池的實(shí)現(xiàn)實(shí)例
- python線程池threadpool實(shí)現(xiàn)篇
相關(guān)文章
Pytorch上下采樣函數(shù)--interpolate用法
這篇文章主要介紹了Pytorch上下采樣函數(shù)--interpolate用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
python實(shí)現(xiàn)多層感知器MLP(基于雙月數(shù)據(jù)集)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多層感知器MLP,基于雙月數(shù)據(jù)集,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
在Python運(yùn)行時(shí)動(dòng)態(tài)查看進(jìn)程內(nèi)部信息的方法
今天小編就為大家分享一篇在Python運(yùn)行時(shí)動(dòng)態(tài)查看進(jìn)程內(nèi)部信息的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
Python利用os模塊實(shí)現(xiàn)自動(dòng)刪除磁盤文件
你們一定想不到os模塊還可以這樣玩,本文就將利用Python中的os模塊實(shí)現(xiàn)自動(dòng)刪除磁盤文件功能,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2022-11-11
Python利用contextvars實(shí)現(xiàn)管理上下文變量
Python?在?3.7?的時(shí)候引入了一個(gè)模塊:contextvars,從名字上很容易看出它指的是上下文變量。所以本文就來(lái)和大家詳細(xì)講講如何使用contextvars實(shí)現(xiàn)管理上下文變量,需要的可以參考一下2022-07-07
python中pandas.read_csv()函數(shù)的深入講解
這篇文章主要給大家介紹了關(guān)于python中pandas.read_csv()函數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python實(shí)現(xiàn)列表中由數(shù)值查到索引的方法
今天小編就為大家分享一篇python實(shí)現(xiàn)列表中由數(shù)值查到索引的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
Django admin model 漢化顯示文字的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Django admin model 漢化顯示文字的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08

