python 绝版线程池
2.绝版线程池
设计思路:运用队列queue
a.队列里面放任务
b.线程一次次去取任务,线程一空闲就去取任务
import queue
import threading
import contextlib
import time
StopEvent = object()
class ThreadPool(object):
def __init__(self, max_num, max_task_num = None):
if max_task_num:
self.q = queue.Queue(max_task_num)
else:
self.q = queue.Queue()
self.max_num = max_num
self.cancel = False
self.terminal = 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
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, args, callback = event
try:
result = func(*args)
success = True
except Exception as e:
success = False
result = None
if callback is not None:
try:
callback(success, result)
except Exception as e:
pass
with self.worker_state(self.free_list, current_thread):
if self.terminal:
event = StopEvent
else:
event = self.q.get()
else:
self.generate_list.remove(current_thread)
def close(self):
"""
执行完所有的任务后,所有线程停止
"""
self.cancel = True
count = len(self.generate_list)
while count:
self.q.put(StopEvent)
count -= 1
def terminate(self):
"""
无论是否还有任务,终止线程
"""
self.terminal = True
while self.generate_list:
self.q.put(StopEvent)
self.q.queue.clear()
@contextlib.contextmanager
def worker_state(self, state_list, worker_thread):
"""
用于记录线程中正在等待的线程数
"""
state_list.append(worker_thread)
try:
yield
finally:
state_list.remove(worker_thread)
# How to use
pool = ThreadPool(5)
def callback(status, result):
# status, execute action status
# result, execute action return value
pass
def action(i):
print(i)
for i in range(30):
ret = pool.run(action, (i,), callback)
time.sleep(3)
print(len(pool.generate_list), len(pool.free_list))
print(len(pool.generate_list), len(pool.free_list))
pool.close()
# pool.terminate()
python 绝版线程池的更多相关文章
- Python的线程池实现
# -*- coding: utf-8 -*- #Python的线程池实现 import Queue import threading import sys import time import ur ...
- 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 ...
随机推荐
- [HDU 1215] 七夕节(求因子,不超时)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1215 //注意怎么处理不超时 #include<iostream> #include< ...
- 常用for循环和for in 以及for of 的区别
用Es6对象扩展运算符(…)与rest运算符说明 function test(first,...a){ for(let val=0; val<a.length;val++){ console.l ...
- 引入jquery利用Vue生命周期的钩子函数mounted操作DOM
html <div id="app"> <div>{{message}}</div> </div> js var vm = new ...
- 在Mac OSX下安装Microsoft Calibri字体
参考: Where can I find default Microsoft fonts Calibri, Cambria? 在Mac OSX下安装Microsoft Calibri字体 1.下载: ...
- 批处理bat标准化获取当前系统日期的几种方法,补0
首先有两个推荐的方案. 一: for /f "tokens=2 delims==" %%a in ('wmic path win32_operatingsystem get Loc ...
- 清除浏览器CSS样式
/* YUI 3.18.1 (build f7e7bcb) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD ...
- mapgis IGServer账号
2064803644@qq.com 1576391020@qq.com 密码一样
- _itemmod_hidden
该表中的物品放在背包或银行中中会计算属性 `entry`物品ID `comment` 备注
- 【二十九】php之简易微信二维码支付
参考二维码支付接口文档:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5 index.php <!DOCTYPE htm ...
- python 启动新进程执行脚本
import subprocess p_restart=subprocess.Popen(['/bin/sh','/etc/init.d/xxx_service','reboot'])