版本一:
#!/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之线程池的更多相关文章
-
Python的线程池实现
# -*- coding: utf-8 -*- #Python的线程池实现 import Queue import threading import sys import time import ur ...
-
Python之路【第八篇】python实现线程池
线程池概念 什么是线程池?诸如web服务器.数据库服务器.文件服务器和邮件服务器等许多服务器应用都面向处理来自某些远程来源的大量短小的任务.构建服务器应用程序的一个过于简单的模型是:每当一个请求到达就 ...
-
python自定义线程池
关于python的多线程,由与GIL的存在被广大群主所诟病,说python的多线程不是真正的多线程.但多线程处理IO密集的任务效率还是可以杠杠的. 我实现的这个线程池其实是根据银角的思路来实现的. 主 ...
-
Python的线程池
#!/usr/bin/env python # -*- coding: utf-8 -*- """ concurrent 用于线程池和进程池编程而且更加容易,在Pytho ...
-
[python] ThreadPoolExecutor线程池 python 线程池
初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...
-
《Python》线程池、携程
一.线程池(concurrent.futures模块) #1 介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 P ...
-
[python] ThreadPoolExecutor线程池
初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...
-
python实现线程池
线程池 简单线程池 import queue import threading import time class ThreadPool(object): #创建线程池类 def __init__(s ...
-
python 绝版线程池
2.绝版线程池设计思路:运用队列queue a.队列里面放任务 b.线程一次次去取任务,线程一空闲就去取任务 import queueimport threadingimport contextlib ...
随机推荐
-
菜鸟-手把手教你把Acegi应用到实际项目中(3)
这一节我们将要了解的是AnonymousProcessingFilter.RememberMeProcessingFilter和LogoutFilter三个过滤器. 1.AnonymousProces ...
-
查看数量linux下查看cpu物理个数和逻辑个数
首先声明,我是一个菜鸟.一下文章中出现技术误导情况盖不负责 hadoop@chw-desktop3:~$ cat /proc/cpuinfo processor : 0 vendor_id : Gen ...
-
James搭建邮件服务器
来源:http://chenfengcn.iteye.com/blog/356874 1 关于James与Javamail Apache James(Java Apache Mail Enterp ...
-
图片生成操作属性导致WP内存溢出解决办法
在开发的项目中,发现经常会出现异常 “内存溢出,不能再继续执行程序”,通过搜索一些国外的文章,发现原来是由于项目中的图片比较多,而生存操作设为了“内容”.通过设置图片的生成操作为“无”,复制操作为“如 ...
-
mysql建表出现Timestamp错误
mysql建表时如果有两个或以上的字段为Timestamp,那么可能会出现如下错误: Incorrect table definition; there can be only one TIMESTA ...
-
(转)iOS消息推送机制中pem文件的生成
转自:http://2015.iteye.com/blog/1567777 以前写了一篇文章:iOS消息推送机制的实现,这篇文章中生成的是p12文件,但是php是用的pem文件,生成的方法和p12文件 ...
-
JVM学习笔记三:垃圾收集器与内存分配策略
内存回收与分配重点关注的是堆内存和方法区内存(程序计数器占用小,虚拟机栈和本地方法栈随线程有相同的生命周期). 一.判断对象是否存活? 1. 引用计数算法 优势:实现简单,效率高. 致命缺陷:无法解决 ...
-
C#2.0 迭代器
迭代器 迭代器模式是和为模式的一种范例,我们访问数据序列中所有的元素,不用关心序列是什么类型.从数据管道中数据经过一系列不同的转换或过滤后从管道的另一端出来. 像数组.集合等已经内置了迭代器,我们可以 ...
-
Linux systemctl 命令完全指南
Systemctl是一个systemd工具,主要负责控制systemd系统和服务管理器. Systemd是一个系统管理守护进程.工具和库的集合,用于取代System V初始进程.Systemd的功能是 ...
-
Golang 之协程详解
转自:https://www.cnblogs.com/liang1101/p/7285955.html 一.Golang 线程和协程的区别 备注:需要区分进程.线程(内核级线程).协程(用户级线程)三 ...