版本一:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import threading class ThreadPool(object): def __init__(self, max_num=20):
self.queue = Queue.Queue(max_num)
for i in xrange(max_num):
self.queue.put(threading.Thread) def get_thread(self):
return self.queue.get() def add_thread(self):
self.queue.put(threading.Thread) """
pool = ThreadPool(10) def func(arg, p):
print arg
import time
time.sleep(2)
p.add_thread() for i in xrange(30):
thread = pool.get_thread()
t = thread(target=func, args=(i, pool))
t.start()
"""

版本一

  版本二:

#!/usr/bin/env python
# -*-coding:utf-8 -*- import threading
import time
import queue
import contextlib StopEvent = object() class Threading(object): def __init__(self,maxthread):
# 任务队列
self.q=queue.Queue()
# 最大线程数
self.MaxThread = maxthread
# 空闲线程列表
self.free_thread = []
# 已经创建的线程
self.generate_list = []
# 中断执行标志位
self.terminal = False def run(self,func,args,callback=None):
w = (func,args,callback)
self.q.put(w)
if len(self.free_thread) == 0 and len(self.generate_list) < self.MaxThread:
self.create_thread() def create_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:
status = True
func, args, callback = event try :
ret = func(args)
except Exception as e:
status = False
ret = e
if callback is not None:
try:
callback(status,ret)
except Exception as e:
pass
else:
pass if self.terminal:
event = StopEvent
else:
with self.worker_state(self.free_thread,current_thread):
event = self.q.get() else:
self.generate_list.remove(current_thread) def close(self):
num = len(self.generate_list)
while num :
self.q.put(StopEvent)
num -=1 def terminate(self):
self.terminal = True while self.generate_list:
self.q.put(StopEvent) self.q.empty() @contextlib.contextmanager
def worker_state(self, state_list, worker_thread):
state_list.append(worker_thread)
try:
yield
finally:
state_list.remove(worker_thread) def action(i):
time.sleep(0.5)
print(i) def callback(status , ret):
print(status,ret) if __name__ == '__main__': pool = Threading(10) for i in range(50):
pool.run(action , i ) # pool.terminate()
pool.close()

版本二

【Python之路】特别篇--Python线程池的更多相关文章

  1. Python之路(第九篇)Python文件操作

    一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r",encoding = “utf ...

  2. Python之路,Day9, 进程、线程、协程篇

    本节内容 操作系统发展史介绍 进程.与线程区别 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Event事件 queue队列 生产者 ...

  3. 【Python之路】特别篇--Python面向对象(进阶篇)

    上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  4. 【Python之路】特别篇--Python面向对象(初级篇)

    概述 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发“更快更好更强...” 面向过程编程最易被初学 ...

  5. python(13)多线程:线程池,threading

    python 多进程:多进程 先上代码: pool = threadpool.ThreadPool(10) #建立线程池,控制线程数量为10 reqs = threadpool.makeRequest ...

  6. python第十一天-----补:线程池

    低版本: #!/usr/bin/env python import threading import time import queue class TreadPool: ""&q ...

  7. python之路基础篇

    基础篇 1.Python基础之初识python 2.Python数据类型之字符串 3.Python数据类型之列表 4.Python数据类型之元祖 5.Python数据类型之字典 6.Python Se ...

  8. Python并发复习4- concurrent.futures模块(线程池和进程池)

    Python标准库为我们提供了threading(多线程模块)和multiprocessing(多进程模块).从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提 ...

  9. python之路入门篇

    一. Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,Guido开始写能够解释Python语言语法的解释器.Python这个名字,来 ...

  10. python之路第一篇

    一.python环境的搭建 1.window下环境的搭建 (1).在 https://www.python.org/downloads/ 下载自己系统所需要的python版本 (2).安装python ...

随机推荐

  1. 引用Nuget包Microsoft.EntityFrameworkCore.Tools.DotNet报错

    错误如下 解决方法 使用VS2017或更高版本在改项目右键,选择“编辑xxx.csproj”,并添加如下一句话,就可以成功引用改Nuget包 <PackageReference Include= ...

  2. Logger Rate Limiter

    Design a logger system that receive stream of messages along with its timestamps, each message shoul ...

  3. Redundant Connection

    In this problem, a tree is an undirected graph that is connected and has no cycles. The given input ...

  4. Java基础(六)

    面向对象 概述 生活举例 代码体验 类与对象的关系 类的定义 根据类创建对象 对象的基本使用 练习:手机类与对象 内存图:一个对象 内存图:两个对象 内存图:同一个对象 局部变量与成员变量的区别 pr ...

  5. Oracle集群检测命令

    select inst_id, count(inst_id) from gv$session group by inst_id order by inst_id; srvctl stop databa ...

  6. <<C++ Primer>> 第 7 章 类

    术语表 第 7 章 类 抽象数据类型(abstract data type): 封装(隐藏)了实现细节的数据结构.    访问说明符(access specifier): 包括关键字 public 和 ...

  7. redis 学习(6)-- 集合类型

    redis 学习(6)-- 集合类型 set 结构 无序 无重复 集合间操作 set 集合内操作 命令 含义 sadd key memebr1 [member2...] 向集合中添加一个或多个成员 s ...

  8. eclipse 保存web.xml 和 loading description from 问题的解决

    Eclipse 版本为 2019-06 (4.12.0) 发现开启的时候一直有loading description from ***  ,这个loading description 是web项目加载 ...

  9. 转载:elasticsearch入门篇

    转自:https://www.cnblogs.com/hello-shf/p/11543408.html elasticsearch入门篇   elasticsearch专栏:https://www. ...

  10. 自己实现一个简化版的SpringMVC框架

    废话不多说,我们进入今天的正题,在Web应用程序设计中,MVC模式已经被广泛使用.SpringMVC以DispatcherServlet为核心,负责协调和组织不同组件以完成请求处理并返回响应的工作,实 ...