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()
Python线程池中,可以使用`submit`方法提交多个参数给函数。通过`ThreadPoolExecutor.submit(fn, *args, **kwargs)`方法,可以将`fn`函数提交给线程池执行,并通过`*args`传递多个参数,以关键字参数的形式通过`**kwargs`传递其他参数。这样,线程池会异步执行`fn`函数,并将多个参数传递给该函数。 举例来说,如果有一个函数`my_func`需要接收两个参数`param1`和`param2`,你可以使用线程池的`submit`方法来执行该函数,并传递多个参数: ``` from concurrent.futures import ThreadPoolExecutor def my_func(param1, param2): # 函数体 # 创建线程池 executor = ThreadPoolExecutor() # 提交函数并传递多个参数 future = executor.submit(my_func, arg1, arg2) ``` 在这个例子中,`my_func`函数被提交给线程池,并通过`arg1`和`arg2`作为参数传递给该函数。通过`executor.submit`方法返回的`future`对象可以用于获取函数的执行结果或处理其他操作。这样,线程池就可以并发执行具有多个参数的函数了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【python | 线程池】多参数传参](https://blog.youkuaiyun.com/pingyufeng/article/details/128352879)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python学习笔记--python的多线程以及并发操作](https://blog.youkuaiyun.com/weixin_46990115/article/details/126044806)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值