目前项目中有个工作是使用python定时处理数据库中的任务,之前是每个任务都起一个线程进行处理,随着任务数的增多,起的线程也越来越多,最终出现内存溢出情况。
于是在网上查到了线程池的使用,转载代码如下:
#Python的线程池实现
import Queue
import threading
import sys
import time
import urllib
import Log
#替我们工作的线程池中的线程
class MyThread(threading.Thread):
def __init__( workQueue, timeout=30, **kwargs):
threading.Thread.__init__( kwargs=kwargs)
#线程在结束前等待任务队列多长时间
timeout = timeout
setDaemon(True)
workQueue = workQueue
start()
def run(self):
while True:
try:
#从工作队列中获取一个任务
callable, args, kwargs = workQueue.get(timeout = timeout)
#我们要执行的任务
callable(args, kwargs)
#任务队列空的时候结束此线程
except Queue.Empty:
break
except :
print sys.exc_info()
raise
class ThreadPool:
def __init__( num_of_threads=10):
workQueue = Queue.Queue()
threads = []
__createThreadPool( num_of_threads )
def __createThreadPool( num_of_threads ):
for i in range( num_of_threads ):
thread = MyThread( workQueue )
threads.append(thread)
def wait_for_complete():
#等待所有线程完成。
while len(threads):
thread = threads.pop()
#等待线程结束
if thread.isAlive():#判断线程是否还存活来决定是否调用join
thread.join()
def add_job( callable, *args, **kwargs ):
workQueue.put( (callable,args,kwargs) )
def main():
threadpool = ThreadPool(10)
for task in taskList:
threadpool.add_job(task, *args, **kwargs)
threadpool.wait_for_complete()
if __name__ == '__main__':
main()
1153

被折叠的 条评论
为什么被折叠?



