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 -*- """
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 ...
随机推荐
- Android之ADB指令
Android打包过程 aapt Android应用打包工具 adb Android调试桥 下面打包过程,eclipse帮我们自动打包好run as->Android application r ...
- Selenium2+python自动化4-Pycharm使用
前言 在写脚本之前,先要找个顺手的写脚本工具.python是一门解释性编程语言,所以一般把写python的工具叫解释器.写python脚本的工具很多,小编这里就不一一列举的,只要自己用着顺手就可以的, ...
- POJ 3281 Dining
Dining Description Cows are such finicky eaters. Each cow has a preference for certain foods and dri ...
- [转] swf文件加密基础
本来打算下班回来就写这个东西,一方面算是对今天学习的一个笔记记录,另外一方面,给一些朋友普及一些swf文件加密基础知识.之所以说是基础,那是因为我也是刚学习了一点,灰常的基础.不过晚上看了一会我是传奇 ...
- linux下mysql集群的安装
3台redhat服务器: SQL节点(mysqld): 192.168.1.77;192.168.1.78 数据节点(ndbd): 192.168.1.77;192.168.1.78 管理节点(ndb ...
- Linux crontab命令的使用方法
crontab命令常见于Unix和Linux的操作系统之中,用于设置周期性被执行的指令.该命令从标准输入设备读取指令,并将其存放于"crontab"文件中,以供之后读取和执行. 在 ...
- JavaWeb---图书馆管理系统
写在开头,以后每天写记录. 今天,初步了解了一下,项目需求,用现在自己所学的知识,很多还不能做出来. 先用目前的知识,一步步的做出来,不断的完善,今天遇到的问题: 任务分析: 01.list页面的ad ...
- Web 登陆界面---简单模块1
今天学习登陆界面的基本模块,其中几个基本的元素 a元素.form元素.布局元素(table\tr\td).加粗(b).input元素 1.<a href="">内容&l ...
- ascii文件转为utf-8格式
import codecs import os #格式转换 fhanzi1 = codecs.open(os.path.join(outputpath,"hanzi1.txt"), ...
- cinder ha