如何理解接口幂等性
250
2022-09-04
python进程池高级版本(python进程池)
#!/usr/bin/env python# -*- coding: utf-8 -*-import queueimport threadingimport contextlibimport time#全局变量StopEvent = object()class threadpool(object):def __init__(self,max_num):#任务队列self.q = queue.Queue()#正在执行任务的self.generate_list=[]#空闲的self.free_list=[]#最多能创建几个进程self.max_num = max_numdef run(self,func,args,callback=None):if len(self.free_list) == 0 and len(self.generate_list) < self.max_num:#创建线程self.generate_thread()#把任务放入队列w = (func,args,callback,)self.q.put(w)def generate_thread(self):#创建一个线程t = threading.Thread(target=self.call) t.start()def call(self):"""循环执行任务 """ #获取当前进程current_thread = threading.current_thread()self.generate_list.append(current_thread)#去任务并执行event = self.q.get()while event != StopEvent :#是元祖 是任务#解开任务包#去执行func,arguments,callback=eventtry : result = func(*arguments) callback(result)except Exception as e:passself.free_list.append(current_thread) event = self.q.get()self.free_list.remove(current_thread)else :#不是元祖 不是任务self.generate_list.remove(current_thread)pool = threadpool(5)def callback(status, result):# status, execute action status # result, execute action return valuepassdef action(i): time.sleep(1)print(i)for i in range(50): ret = pool.run(action, (i,), callback)time.sleep(5)print(len(pool.generate_list), len(pool.free_list))print(len(pool.generate_list), len(pool.free_list))
C:\Python31\python.exe D:/pythoncode/a8.py
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~