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 绝版线程池的更多相关文章

  1. Python的线程池实现

    # -*- coding: utf-8 -*- #Python的线程池实现 import Queue import threading import sys import time import ur ...

  2. Python之路【第八篇】python实现线程池

    线程池概念 什么是线程池?诸如web服务器.数据库服务器.文件服务器和邮件服务器等许多服务器应用都面向处理来自某些远程来源的大量短小的任务.构建服务器应用程序的一个过于简单的模型是:每当一个请求到达就 ...

  3. Python之线程池

    版本一: #!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(obj ...

  4. python自定义线程池

    关于python的多线程,由与GIL的存在被广大群主所诟病,说python的多线程不是真正的多线程.但多线程处理IO密集的任务效率还是可以杠杠的. 我实现的这个线程池其实是根据银角的思路来实现的. 主 ...

  5. Python的线程池

    #!/usr/bin/env python # -*- coding: utf-8 -*- """ concurrent 用于线程池和进程池编程而且更加容易,在Pytho ...

  6. [python] ThreadPoolExecutor线程池 python 线程池

    初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...

  7. 《Python》线程池、携程

    一.线程池(concurrent.futures模块) #1 介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 P ...

  8. [python] ThreadPoolExecutor线程池

    初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...

  9. python实现线程池

    线程池 简单线程池 import queue import threading import time class ThreadPool(object): #创建线程池类 def __init__(s ...

随机推荐

  1. 用.native修饰器来对外部组件进行构造器内部方法的调用以及用原生js获取构造器里的方法

    html <div id="app"> <span v-text="number"></span> <btn @cli ...

  2. [mybatis错误] - sql出错 org.apache.ibatis.ognl.ParseException: Encountered "!" at line 1, column 15. Was expecting one of:

    完整异常:Caused by: org.apache.ibatis.builder.BuilderException: Error evaluating expression 'developerTy ...

  3. facebook api之基本概念(中文)

    Facebook广告API系列 1 Facebook Graph API Facebook提供了一套类rest的接口,统称为Graph API.为啥叫Graph?因为facebook把所有的资源都抽象 ...

  4. HDU 6215 Brute Force Sorting(链表)

    http://acm.hdu.edu.cn/showproblem.php?pid=6215 题意:给出一个序列,对于每个数,它必须大于等于它前一个数,小于等于后一个数,如果不满足,就删去.然后继续去 ...

  5. 突变注释工具SnpEff,Annovar,VEP,oncotator比较分析--转载

    https://www.jianshu.com/p/6284f57664b9 目前对于variant进行注释的软件主要有4个: Annovar, SnpEff, VEP(variant Effect ...

  6. CSS3动画详解(结合实例)

    一.使用CSS3动画代替JS动画 JS动画频繁操作DOM导致效率非常低 在频繁的操作DOM和CSS时,浏览器会不停的执行重排(reflow)和重绘(repaint) 可以避免占用JS主线程 这边就不细 ...

  7. go 单进程并发

    demo1 // This sample program demonstrates how to create goroutines and // how the scheduler behaves. ...

  8. django人类可读性

    一些Django的‘奇技淫巧’就存在于这些不起眼的地方. 为了提高模板系统对人类的友好性,Django在django.contrib.humanize中提供了一系列的模板过滤器,有助于为数据展示添加“ ...

  9. 一般删除网页数据和jquery下使用Ajax删除数据的区别

    1. 一般删除网页数据 就是指用户在点击删除的时候,会跳转到DeleteUser.ashx一般处理程序中,并且通过get传参的方式传递一个id的参数,然后在后台处理 <a href='Delet ...

  10. 学习笔记13—python DataFrame获取行数、列数、索引及第几行第几列的值

    1. df=DataFrame([{‘A’:’11’,’B’:’12’},{‘A’:’111’,’B’:’121’},{‘A’:’1111’,’B’:’1211’}]) print df.column ...