用python实现的线程池实例代码

yipeiwu_com7年前Python基础

python3标准库里自带线程池ThreadPoolExecutor和进程池ProcessPoolExecutor。

如果你用的是python2,那可以下载一个模块,叫threadpool,这是线程池。对于进程池可以使用python自带的multiprocessing.Pool。

当然也可以自己写一个threadpool。

# coding:utf-8
 
import Queue
import threading
import sys
import time
import math
 
 
class WorkThread(threading.Thread):
 
  def __init__(self, task_queue):
    threading.Thread.__init__(self)
    self.setDaemon(True)
    self.task_queue = task_queue
    self.start()
    self.idle = True
 
  def run(self):
    sleep_time = 0.01 # 第1次无任务可做时休息10毫秒
    multiply = 0
    while True:
      try:
        # 从队列中取一个任务
        func, args, kwargs = self.task_queue.get(block=False)
        self.idle = False
        multiply = 0
        # 执行之
        func(*args, **kwargs)
      except Queue.Empty:
        time.sleep(sleep_time * math.pow(2, multiply))
        self.idle = True
        multiply += 1
        continue
      except:
        print sys.exc_info()
        raise
 
 
class ThreadPool:
 
  def __init__(self, thread_num=10, max_queue_len=1000):
    self.max_queue_len = max_queue_len
    self.task_queue = Queue.Queue(max_queue_len) # 任务等待队列
    self.threads = []
    self.__create_pool(thread_num)
 
  def __create_pool(self, thread_num):
    for i in xrange(thread_num):
      thread = WorkThread(self.task_queue)
      self.threads.append(thread)
 
  def add_task(self, func, *args, **kwargs):
    '''添加一个任务,返回任务等待队列的长度
      调用该方法前最后先调用isSafe()判断一下等待的任务是不是很多,以防止提交的任务被拒绝
    '''
    try:
      self.task_queue.put((func, args, kwargs))
    except Queue.Full:
      raise # 队列已满时直接抛出异常,不给执行
    return self.task_queue.qsize()
 
  def isSafe(self):
    '''等待的任务数量离警界线还比较远
    '''
    return self.task_queue.qsize() < 0.9 * self.max_queue_len
 
  def wait_for_complete(self):
    '''等待提交到线程池的所有任务都执行完毕
    '''
    #首先任务等待队列要变成空
    while not self.task_queue.empty():
      time.sleep(1)
    # 其次,所以计算线程要变成idle状态
    while True:
      all_idle = True
      for th in self.threads:
        if not th.idle:
          all_idle = False
          break
      if all_idle:
        break
      else:
        time.sleep(1)
 
 
if __name__ == '__main__':
  def foo(a, b):
    print a + b
    time.sleep(0.01)
  thread_pool = ThreadPool(10, 100)
  '''在Windows上测试不通过,Windows上Queue.Queue不是线程安全的'''
  size = 0
  for i in xrange(10000):
    try:
      size = thread_pool.add_task(foo, i, 2 * i)
    except Queue.Full:
      print 'queue full, queue size is ', size
  time.sleep(2)

总结

以上就是本文关于用python实现的线程池实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python实现PS滤镜特效之扇形变换效果示例

Python实现PS滤镜特效之扇形变换效果示例

本文实例讲述了Python实现PS滤镜特效之扇形变换效果。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 滤镜中的一种几何变换特效,称为扇形变换,将图像扭曲成一个扇形...

Python计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算的位数 在电脑上做了一个实验,看看python能计算到多少位,一下是结果。 x = math.sqrt((3)) print ("%.53f"%(x)) print...

使用python编写脚本获取手机当前应用apk的信息

前提是已设置ANDROID_HOME环境变量,使用aapt工具获取apk的信息,保存至脚本所在目录下的PackageInfo.txt文件中: import os import te...

Python之dict(或对象)与json之间的互相转化实例

在Python语言中,json数据与dict字典以及对象之间的转化,是必不可少的操作。 在Python中自带json库。通过import json导入。 在json模块有2个方法, lo...

Python使用filetype精确判断文件类型

filetype.py Small and dependency free Python package to infer file type and MIME type checkin...