Python的线程池实现
# -*- coding: utf-8 -*-
#Python的线程池实现
import Queue
import threading
import sys
import time
import urllib
#替我们工作的线程池中的线程
class MyThread(threading.Thread):
def __init__(self, workQueue, resultQueue,timeout=30, **kwargs):
threading.Thread.__init__(self, kwargs=kwargs)
#线程在结束前等待任务队列多长时间
self.timeout = timeout
self.setDaemon(True)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.start()
def run(self):
while True:
try:
#从工作队列中获取一个任务
callable, args, kwargs = self.workQueue.get(timeout=self.timeout)
#我们要执行的任务
res = callable(args, kwargs)
#报任务返回的结果放在结果队列中
self.resultQueue.put(res+" | "+self.getName())
except Queue.Empty: #任务队列空的时候结束此线程
break
except :
print sys.exc_info()
raise
class ThreadPool:
def __init__(self, num_of_threads=10):
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.threads = []
self.__createThreadPool(num_of_threads)
def __createThreadPool(self, num_of_threads):
for i in range(num_of_threads):
thread = MyThread(self.workQueue, self.resultQueue)
self.threads.append(thread)
def wait_for_complete(self):
#等待所有线程完成。
while len(self.threads):
thread = self.threads.pop()
#等待线程结束
if thread.isAlive(): #判断线程是否还存活来决定是否调用join
thread.join()
def add_job(self, callable, *args, **kwargs):
self.workQueue.put((callable,args,kwargs))
def test_job(id, sleep = 0.001):
html = ""
try:
time.sleep(1)
conn = urllib.urlopen('http://www.baidu.com/')
html = conn.read(20)
except:
print sys.exc_info()
return html
def test():
print 'start testing'
tp = ThreadPool(10)
for i in range(50):
time.sleep(0.2)
tp.add_job(test_job, i, i*0.001)
tp.wait_for_complete()
#处理结果
print 'result Queue\'s length == %d '% tp.resultQueue.qsize()
while tp.resultQueue.qsize():
print tp.resultQueue.get()
print 'end testing'
if __name__ == '__main__':
test()
import sys
IS_PY2 = sys.version_info < (3, 0)
if IS_PY2:
from Queue import Queue
else:
from queue import Queue
from threading import Thread
class Worker(Thread):
""" Thread executing tasks from a given tasks queue """
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try:
func(*args, **kargs)
except Exception as e:
# An exception happened in this thread
print(e)
finally:
# Mark this task as done, whether an exception happened or not
self.tasks.task_done()
class ThreadPool:
""" Pool of threads consuming tasks from a queue """
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads):
Worker(self.tasks)
def add_task(self, func, *args, **kargs):
""" Add a task to the queue """
self.tasks.put((func, args, kargs))
def map(self, func, args_list):
""" Add a list of tasks to the queue """
for args in args_list:
self.add_task(func, args)
def wait_completion(self):
""" Wait for completion of all the tasks in the queue """
self.tasks.join()
if __name__ == "__main__":
from random import randrange
from time import sleep
# Function to be executed in a thread
def wait_delay(d):
print("sleeping for (%d)sec" % d)
sleep(d)
# Generate random delays
delays = [randrange(3, 7) for i in range(50)]
# Instantiate a thread pool with 5 worker threads
pool = ThreadPool(5)
# Add the jobs in bulk to the thread pool. Alternatively you could use
# `pool.add_task` to add single jobs. The code will block here, which
# makes it possible to cancel the thread pool with an exception when
# the currently running batch of workers is finished.
pool.map(wait_delay, delays)
pool.wait_completion()
Python的线程池实现的更多相关文章
- Python之路【第八篇】python实现线程池
线程池概念 什么是线程池?诸如web服务器.数据库服务器.文件服务器和邮件服务器等许多服务器应用都面向处理来自某些远程来源的大量短小的任务.构建服务器应用程序的一个过于简单的模型是:每当一个请求到达就 ...
- Python之线程池
版本一: #!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(obj ...
- 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 ...
随机推荐
- Flask之flask-script 指定端口
简介 Flask-Scropt插件为在Flask里编写额外的脚本提供了支持.这包括运行一个开发服务器,一个定制的Python命令行,用于执行初始化数据库.定时任务和其他属于web应用之外的命令行任务的 ...
- [转] Spring Boot特性
[From] http://blog.javachen.com/2015/03/13/some-spring-boot-features.html 1. SpringApplication Sprin ...
- vue项目构建过程
# template 模版项目 > A Vue.js project* 构建过程* 安装过程* 差异点* 打包优化 ## 构建过程```bashbogon:vue-cli caoke$ vue ...
- 【研究】ms17-010永恒之蓝漏洞复现
1 永恒之蓝漏洞复现(ms17-010) 1.1 漏洞描述: Eternalblue通过TCP端口445和139来利用SMBv1和NBT中的远程代码执行漏洞,恶意代码会扫描开放44 ...
- 基于memcache的缓存机制的6个指令
Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached ...
- shell 进阶变量的指定 declare
declare 设置 -r 只读 -i 设置整形 -a 数组 让指定的函数成为一个数组 -f 函数 如果在脚本中使用declare -f, 而不加任何参数的话, 那么将会列出这个脚本之前定义的所有函数 ...
- 路由器中带宽设置(Bandwidth) 20MHZ/40MHZ
原文是英文的,在这里:http://routerguide.net/setting-up-20-mhz-or-40-mhz-bandwidth-how-to-improve-wifi-network- ...
- vue中遇到的坑 --- 变化检测问题(数组相关)
最近在项目中遇到了一个问题,不知道为什么,所以最后通过动手做demo实践.查文档的方式解决了,这里做一个总结. 例1 <!DOCTYPE html> <html lang=" ...
- Apache Beam的架构概览
不多说,直接上干货! Apache Beam是一个开源的数据处理编程库,由Google贡献给Apache的项目,前不久刚刚成为Apache TLP项目.它提供了一个高级的.统一的编程模型,允许我们通过 ...
- 2、java内存间交互操作
关于主内存与工作内存之间具体的交互协议,即一个变量如何从主内存拷贝到工作内存,如何从工作内存同步回主内存之类的实现细节,java内存模型中定义了8种操作来完成,虚拟机实现时必须保证这8种操作都是原子的 ...