版本一:

#!/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 -*- """
custom ThreadPool How to use: pool = ThreadPool(1) def callback(status, result):
# status, execute action status
# result, execute action return value pass
def action(i):
pass for i in range(20):
if pool.stop:
pool.terminal()
break
ret = pool.run(action, (i,), callback) print 'end' """ import Queue
import threading
import contextlib StopEvent = object() class ThreadPool(object): def __init__(self, max_num):
self.q = Queue.Queue(max_num)
self.max_num = max_num
self.cancel = False
self.generate_list = []
self.free_list = [] def run(self, func, args, callback=None):
"""
线程池执行一个任务
:param func: 任务函数
:param args: 任务函数所需参数
:param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数)
:return: 如果线程池已经终止,则返回True否则None
"""
if self.cancel:
return True
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.currentThread
self.generate_list.append(current_thread) event = self.q.get()
while event != StopEvent:
func, arguments, callback = event
try:
result = func(*arguments)
success = True
except Exception, e:
success = False
result = None if callback is not None:
try:
callback(success, result)
except Exception, e:
pass with self.worker_state(self.free_list, current_thread):
event = self.q.get()
else: self.generate_list.remove(current_thread) def terminal(self):
"""
终止线程池中的所有线程
"""
self.cancel = True
full_size = len(self.generate_list)
while full_size:
self.q.put(StopEvent)
full_size -= 1 @contextlib.contextmanager
def worker_state(self, state_list, worker_thread):
"""
用于记录线程中正在等待的线程数
"""
state_list.append(worker_thread)
try:
yield
finally:
state_list.remove(worker_thread)

更多参见:twisted.python.threadpool

上下文管理:https://docs.python.org/2/library/contextlib.html

Python之线程池的更多相关文章

  1. Python的线程池实现

    # -*- coding: utf-8 -*- #Python的线程池实现 import Queue import threading import sys import time import ur ...

  2. Python之路【第八篇】python实现线程池

    线程池概念 什么是线程池?诸如web服务器.数据库服务器.文件服务器和邮件服务器等许多服务器应用都面向处理来自某些远程来源的大量短小的任务.构建服务器应用程序的一个过于简单的模型是:每当一个请求到达就 ...

  3. python自定义线程池

    关于python的多线程,由与GIL的存在被广大群主所诟病,说python的多线程不是真正的多线程.但多线程处理IO密集的任务效率还是可以杠杠的. 我实现的这个线程池其实是根据银角的思路来实现的. 主 ...

  4. Python的线程池

    #!/usr/bin/env python # -*- coding: utf-8 -*- """ concurrent 用于线程池和进程池编程而且更加容易,在Pytho ...

  5. [python] ThreadPoolExecutor线程池 python 线程池

    初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...

  6. 《Python》线程池、携程

    一.线程池(concurrent.futures模块) #1 介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 P ...

  7. [python] ThreadPoolExecutor线程池

    初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...

  8. python实现线程池

    线程池 简单线程池 import queue import threading import time class ThreadPool(object): #创建线程池类 def __init__(s ...

  9. python 绝版线程池

    2.绝版线程池设计思路:运用队列queue a.队列里面放任务 b.线程一次次去取任务,线程一空闲就去取任务 import queueimport threadingimport contextlib ...

随机推荐

  1. poj 2584 T-Shirt Gumbo (二分匹配)

    T-Shirt Gumbo Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2571   Accepted: 1202 Des ...

  2. JS打印页面

         打印 整个html页面(PS:样式要写在页面里面才能打印(就是用内部样式))             <a id="dayi" runat="server ...

  3. CWebBrowser2获取html的内容

    m_web为浏览器控件的变量名 LPDISPATCH p=m_web.GetDocument(); CComQIPtr<IHTMLDocument2,&IID_IHTMLDocument ...

  4. Spring IOC容器中注入bean

    一.基于schema格式的注入 1.基本的注入方式 (属性注入方式) 根据setXxx()方法进行依赖注入,Spring只会检查是否有setter方法,是否有对应的属性不做要求 <bean id ...

  5. ng-repeat指令应用

    1.ng-repeat 一看就知道跟foreach等指令类似,用于循环重复.一般用于列表和表格中.用法如下: <tr ng-repeat="data in dataList" ...

  6. sqlserver,mysql,oracle通用的模拟和改进的全文搜索算法

    问:数据库效率最低的地方是什么? 答:表扫描 问:表扫描常见的情况是 答:like '%a%' 这类查询 如果使用全文检索引擎,又无法满足我们的需求的时候怎么办,比如要从 一个商品名称 "农 ...

  7. Leveldb之version与version_set详细对比

    version类包含的重要变量: VersionSet* vset_; // VersionSet to which this Version belongs Version* next_; // N ...

  8. vb.net下载代码

    '后台 Partial Public Class Download2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender ...

  9. Jade之Code

    Code jade支持内嵌js的代码到jade代码之中. Unbuffered Code 无缓冲代码以-符号开始,无任何额外输出(文本是什么即是什么). jade: - for (var x = 0; ...

  10. C# async await 学习笔记1

    由于我的开发工具为vs.net 2010(.net 4.0),需先做以下两步才能进行: 1.下载并安装Async CTP (http://www.microsoft.com/en-us/downloa ...