Python之路:线程池
版本一
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import Queue
import threading class ThreadPool(object):
#创建类
def __init__(self, max_num=20):#进程函数,默认最大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)#间隔2秒
p.add_thread() for i in xrange(30):#循环进程
thread = pool.get_thread()
t = thread(target=func, args=(i, pool))#传值到func函数,并且执行
t.start()
版本二
from Queue import Queue
import contextlib
import threading
WorkerStop = object()
class ThreadPool:
workers = 0
threadFactory = threading.Thread
currentThread = staticmethod(threading.currentThread)
def __init__(self, maxthreads=20, name=None):
self.q = Queue(0)
self.max = maxthreads
self.name = name
self.waiters = []
self.working = []
def start(self):
while self.workers < min(self.max, self.q.qsize()+len(self.working)):
self.startAWorker()
def startAWorker(self):
self.workers += 1
name = "PoolThread-%s-%s" % (self.name or id(self), self.workers)
newThread = self.threadFactory(target=self._worker, name=name)
newThread.start()
def callInThread(self, func, *args, **kw):
self.callInThreadWithCallback(None, func, *args, **kw)
def callInThreadWithCallback(self, onResult, func, *args, **kw):
o = (func, args, kw, onResult)
self.q.put(o)
@contextlib.contextmanager
def _workerState(self, stateList, workerThread):
stateList.append(workerThread)
try:
yield
finally:
stateList.remove(workerThread)
def _worker(self):
ct = self.currentThread()
o = self.q.get()
while o is not WorkerStop:
with self._workerState(self.working, ct):
function, args, kwargs, onResult = o
del o
try:
result = function(*args, **kwargs)
success = True
except:
success = False
if onResult is None:
pass
else:
pass
del function, args, kwargs
if onResult is not None:
try:
onResult(success, result)
except:
#context.call(ctx, log.err)
pass
del onResult, result
with self._workerState(self.waiters, ct):
o = self.q.get()
def stop(self):
while self.workers:
self.q.put(WorkerStop)
self.workers -= 1
"""
def show(arg):
import time
time.sleep(1)
print arg
pool = ThreadPool(20)
for i in range(500):
pool.callInThread(show, i)
pool.start()
pool.stop()
"""
Python之路:线程池的更多相关文章
- Python之路——线程池
1 线程基础 1.1 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2 线程同步——锁 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样,其实Python中是伪多线程).但是当线程 ...
- python day 20: 线程池与协程,多进程TCP服务器
目录 python day 20: 线程池与协程 2. 线程 3. 进程 4. 协程:gevent模块,又叫微线程 5. 扩展 6. 自定义线程池 7. 实现多进程TCP服务器 8. 实现多线程TCP ...
- 『Python』 ThreadPool 线程池模板
Python 的 简单多线程实现 用 dummy 模块 一句话就可以搞定,但需要对线程,队列做进一步的操作,最好自己写个线程池类来实现. Code: # coding:utf-8 # version: ...
- Python 多线程和线程池
一,前言 进程:是程序,资源集合,进程控制块组成,是最小的资源单位 特点:就对Python而言,可以实现真正的并行效果 缺点:进程切换很容易消耗cpu资源,进程之间的通信相对线程来说比较麻烦 线程:是 ...
- python爬虫之线程池和进程池
一.需求 最近准备爬取某电商网站的数据,先不考虑代理.分布式,先说效率问题(当然你要是请求的太快就会被封掉,亲测,400个请求过去,服务器直接拒绝连接,心碎),步入正题.一般情况下小白的我们第一个想到 ...
- python小demo-01: 线程池+多进程实现cpu密集型操作
起因: 公司有一个小项目,大概逻辑如下: 服务器A会不断向队列中push消息,消息主要内容是视频的地址,服务器B则需要不断从队列中pop消息,然后将该视频进行剪辑最终将剪辑后的视频保存到云服务器.个人 ...
- 【Python】多线程-线程池使用
1.学习目标 线程池使用 2.编程思路 2.1 代码原理 线程池是预先创建线程的一种技术.线程池在还没有任务到来之前,创建一定数量的线程,放入空闲队列中.这些线程都是处于睡眠状态,即均为启动,不消耗 ...
- python之路----线程
线程概念的引入背景 进程 程序并不能单独运行,只有将程序装载到内存中,系统为它分配资源才能运行,而这种执行的程序就称之为进程.程序和进程的区别就在于:程序是指令的集合,它是进程运行的静态描述文本:进程 ...
- python爬虫14 | 就这么说吧,如果你不懂python多线程和线程池,那就去河边摸鱼!
你知道吗? 在我的心里 你是多么的重要 就像 恩 请允许我来一段 freestyle 你们准备好了妹油 你看 这个碗 它又大又圆 就像 这条面 它又长又宽 你们 在这里 看文章 觉得 很开心 就像 我 ...
- Python爬虫之线程池
详情点我跳转 关注公众号"轻松学编程"了解更多. 一.为什么要使用线程池? 对于任务数量不断增加的程序,每有一个任务就生成一个线程,最终会导致线程数量的失控,例如,整站爬虫,假设初 ...
随机推荐
- word、pdf、ppt 转为图片
office word文档.pdf文档.powerpoint幻灯片是非常常用的文档类型,在现实中经常有需求需要将它们转换成图片 -- 即将word.pdf.ppt文档的每一页转换成一张对应的图片,就像 ...
- MVC 项目中又一新方法实现依懒注入 (AutoFac)
详情请查看:http://docs.autofac.org/en/latest/integration/mvc.html#quick-start
- linux 配置tomcat服务器
1. 找到tomcat安装包 find / -name apache-tomcat* 2. 解压包 tar zxvf apache-tomcat-7.0.67.tar.gz rpm -ivh j ...
- 其他信息: Error creating context 'spring.root': 未能加载文件或程序集“EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”或它的某一个依赖项
详细错误情况: “System.Configuration.ConfigurationErrorsException”类型的异常在 Spring.Core.dll 中发生,但未在用户代码中进行处理 其 ...
- 关于安卓HTTP请求用HttpUrlConnection还是HttpClient好
安卓和JAVA应用开发少不了要提交HTTP请求,而基本上目前有两个实现方式:HttpUrlConnection(即URL.openConnection)和HttpClient. 网上不少人都认为Htt ...
- Flex4.6 DataGrid GridItemRenderer宣染器
本文转自:http://blog.sina.com.cn/s/blog_71848dcf01012ctl.html,稍作修改 <?xml version="1.0" enco ...
- Dense Subsequence
Dense Subsequence time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- Note over Chinese Encodings
I been confused years ago. Till recently I collected my thoughts together, and now I am clear about ...
- iOS8中的动态文本
原文链接 : Swift Programming 101: Mastering Dynamic Type in iOS 8 原文作者 : Kevin McNeish Apple声称鼓励第三方App能够 ...
- hdu 2647 Reward(拓扑排序,反着来)
Reward Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total Submis ...