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 ...
随机推荐
- HTML、CSS小知识--兼容IE的下拉选择框select
HTML <div class="s_h_ie"> <select id="Select1" disabled="disabled& ...
- Linux crontab命令的使用方法
crontab命令常见于Unix和Linux的操作系统之中,用于设置周期性被执行的指令.该命令从标准输入设备读取指令,并将其存放于"crontab"文件中,以供之后读取和执行. 在 ...
- ghost 还原系统时,遇到error 10010,提示can not open image file
昨天系统有点问题,在用Ghost还原系统时,一直提示10010错误,提示can not open image file 想着可能是备份文件的问题,从另一台电脑上重新拷过来一份,仍然不行,Ghost还是 ...
- Oracle中的带参数的视图--我们致力于打造人力资源软件
创建包和包体 create or replace package pkg_pv is procedure set_pv(pv varchar2); function get_pv return var ...
- Android入门
在学Android,摘自<第一行代码——Android> 布局管理 通过xml文件进行布局管理. android:id="@+id/button_1" 为当前的元素定义 ...
- UITableViewCell重用的问题
UITableView中有两种重用Cell的方法: - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; - (id)dequ ...
- PopupWindow
以前对于提示类型UI用到了PopupWindow 通过构造函数或者setContentView(View contentView)可以设置其显示内容: 显示时showAtLocation(View p ...
- echo中的逗号
作为一个自学PHP的小白来说,echo是用来打印字符串的,总结几种输入方式如下: $a = 'good morning'; echo $a; echo $a . 'boys'; echo " ...
- 【转】require.js学习笔记(二)
require.js遵循AMD规范,通过define定义模块,require异步加载模块,一个js文件即一个模块. 一.模块加载require1.加载符合AMD规范模块 HTML: <scrip ...
- [Leetcode][JAVA] Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...