【Python之路】特别篇--Python线程池
版本一:
#!/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线程池的更多相关文章
- Python之路(第九篇)Python文件操作
一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r",encoding = “utf ...
- Python之路,Day9, 进程、线程、协程篇
本节内容 操作系统发展史介绍 进程.与线程区别 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Event事件 queue队列 生产者 ...
- 【Python之路】特别篇--Python面向对象(进阶篇)
上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...
- 【Python之路】特别篇--Python面向对象(初级篇)
概述 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发“更快更好更强...” 面向过程编程最易被初学 ...
- python(13)多线程:线程池,threading
python 多进程:多进程 先上代码: pool = threadpool.ThreadPool(10) #建立线程池,控制线程数量为10 reqs = threadpool.makeRequest ...
- python第十一天-----补:线程池
低版本: #!/usr/bin/env python import threading import time import queue class TreadPool: ""&q ...
- python之路基础篇
基础篇 1.Python基础之初识python 2.Python数据类型之字符串 3.Python数据类型之列表 4.Python数据类型之元祖 5.Python数据类型之字典 6.Python Se ...
- Python并发复习4- concurrent.futures模块(线程池和进程池)
Python标准库为我们提供了threading(多线程模块)和multiprocessing(多进程模块).从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提 ...
- python之路入门篇
一. Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,Guido开始写能够解释Python语言语法的解释器.Python这个名字,来 ...
- python之路第一篇
一.python环境的搭建 1.window下环境的搭建 (1).在 https://www.python.org/downloads/ 下载自己系统所需要的python版本 (2).安装python ...
随机推荐
- selenium爬虫后上传数据库。
一.准备工作 1.1安装软件 安装python.安装谷歌浏览器.将chromedriver.exe放到指定位置.放到Scripts文件夹中.我这边的路径为:C:\Users\1\AppData\Loc ...
- Ubuntu-虚拟机-忘记登陆密码
前提 在我们使用Ubuntu虚拟机的过程中,偶尔会出现密码忘了的尴尬事情.里面又有重要资料,不能重新安装,这时我们要重置密码,接下来,让我们共同学习! 重启虚拟机-重启时按住 shift 会出现以下 ...
- CF 1133C Balanced Team
题目链接:http://codeforces.com/problemset/problem/1133/C 题目分析 (个人感受:我看错了题目,硬是写了近一个小时!) 这个题目要求一个最长的序列,使得这 ...
- 双指针(最大删除子串)Codeforces Round #579 (Div. 3)--Remove the Substring (hard version)
题目链接:https://codeforces.com/contest/1203/problem/D2 题意: 给你S串.T串,问你最长删除多长的子串使得S串里仍然有T的子序列. 思路: 想了好久,先 ...
- composer命令介绍之install和update及其区别
composer 是 php 的一个依赖管理工具.它允许你申明项目所依赖的代码库,它会在你的项目中为你安装他们. 然而,对于如何『安装他们』,新手可能并不清楚.网上的答案有的说 composer in ...
- CentOS7实现Nginx+Tomcat 负载均衡
0. 说明 将nginx作为负载均衡器,反向代理,tomcat作为节点服务器 192.168.100.201:nginx服务器 192.168.100.202:Tomcat 1服务器 192.168. ...
- 第一章 T-SQL查询和编程基础 T-SQL语言基础(2)
T-SQL查询和编程基础 (2) 1.3 创建表和定义数据完整性 注意:表是属于架构,而架构又是属于数据库的 -- Create a database called testdb IF DB_ID(' ...
- luogu P3826 [NOI2017]蔬菜
luogu 那个第一次购买有\(s_i\)奖励,可以看成是多一种蔬菜\(i+n\),权值为\(w_i+s_i\),每天减少量\(x\)为0个,保质期\(\lceil\frac{c_i}{x_i}\rc ...
- 响应式网页,让div的高和宽保持等比例放大、缩小
1,方案一:响应式来做,可以根据媒体查询,设定在不同屏幕宽度下div的高度和宽度,具体的设置看你响应式想怎么显示 @media only screen and (min-width: 100px) a ...
- python中format所有用法
平时只用参数匹配,偶尔看到别人的format用法楞住没反应过来,遂记下 #通过位置 print '{0},{1}'.format('hehe',20) print '{},{}'.format('he ...