python3標準庫里自帶執行緒池threadpoolexecutor
和程序池processpoolexecutor
。當然也可以自己寫乙個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次無任務可做時休息10毫秒
multiply = 0
while true:
try:
# 從佇列中取乙個任務
func, args, kwargs = self.task_queue.get(block=false)
self.idle = false
multiply = 0
# 執行之
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) # 任務等待佇列
self.threads =
self.__create_pool(thread_num)
def __create_pool(self, thread_num):
for i in xrange(thread_num):
thread = workthread(self.task_queue)
def add_task(self, func, *args, **kwargs):
'''新增乙個任務,返回任務等待佇列的長度
呼叫該方法前最後先呼叫issafe()判斷一下等待的任務是不是很多,以防止提交的任務被拒絕
'''try:
self.task_queue.put((func, args, kwargs))
except queue.full:
raise # 佇列已滿時直接丟擲異常,不給執行
return self.task_queue.qsize()
def issafe(self):
'''等待的任務數量離警界線還比較遠
'''return self.task_queue.qsize() < 0.9 * self.max_queue_len
def wait_for_complete(self):
'''等待提交到執行緒池的所有任務都執行完畢
'''#首先任務等待佇列要變成空
while not self.task_queue.empty():
time.sleep(1)
# 其次,所以計算執行緒要變成idle狀態
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上測試不通過,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)
用 Python 實現的執行緒池
用 python 實現的執行緒池 用 python 實現的執行緒池 軟體技術 lhwork 發表於 2007 2 1 8 53 26 為了提高程式的效率,經常要用到多執行緒,尤其是io等需要等待外部響應的部分。執行緒的建立 銷毀和排程本身是有代價的,如果乙個執行緒的任務相對簡單,那這些時間和空間開銷...
用python建立執行緒池
物件導向開發中,大家知道建立和銷毀物件是很費時間的,因為建立乙個物件要獲取記憶體資源或者其它更多資源。無節制的建立和銷毀執行緒是一種極大的浪費。那我們可不可以把執行完任務的執行緒不銷毀而重複利用呢?彷彿就是把這些執行緒放進乙個池子,一方面我們可以控制同時工作的執行緒數量,一方面也避免了建立和銷毀產生...
Python的執行緒池實現
實現 coding utf 8 import queue import threading import sys import time import urllib 替我們工作的執行緒池中的執行緒 class mythread threading.thread def init self,workq...