• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
python进程池高级版本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import queue
import threading
import contextlib
import 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_num

def 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=event
try :
result = func(*arguments)
callback(result)
except Exception as e:
pass

self.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 value
pass


def 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
1
0
2
4
3
7
6
6
5
9
8
10
11
12
13
14
15
18
16
17
19
5 0
5 0
20
21
20
24
23
22
25
26
29
29
28
29
28
27
30
31
30
32
34
33
35
36
39
39
38
37
40
40
41
43
43
44
43
44
42
46
45
48
49
47
 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8691568.html

posted on 2018-04-02 11:21  孙龙-程序员  阅读(103)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3