Python笔记(五) -- Python线程池

目前项目中有个工作是使用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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值