Python实现的自定义多线程多进程类示例


Posted in Python onMarch 23, 2018

本文实例讲述了Python实现的自定义多线程多进程类。分享给大家供大家参考,具体如下:

最近经常使用到对大量文件进行操作的程序以前每次写的时候都要在函数中再写一个多线程多进程的函数,做了些重复的工作遇到新的任务时还要重写,因此将多线程与多进程的一些简单功能写成一个类,方便使用。功能简单只为以后方便使用。

使用中发现bug会再进行更新

#!/usr/bin/env python
  # -*- coding: utf-8 -*-
  # @Time  : 2017/5/10 12:47
  # @Author : zhaowen.zhu
  # @Site  :
  # @File  : MultiThread.py
  # @Software: Python Idle
  import threading,time,sys,multiprocessing
  from multiprocessing import Pool
  class MyTMultithread(threading.Thread):
    '''''
    自定义的线程函数,
    功能:使用多线程运行函数,函数的参数只有一个file,并且未实现结果值的返回
    args:
      filelist  函数的参数为列表格式,
      funname  函数的名字为字符串,函数仅有一个参数为file
      delay   每个线程之间的延迟,
      max_threads 线程的最大值
    '''
    def __init__(self,filelist,delay,funname,max_threads = 50):
      threading.Thread.__init__(self)
      self.funname = funname
      self.filelist = filelist[:]
      self.delay = delay
      self.max_threads = max_threads
    def startrun(self):
      def runs():
        time.sleep(self.delay)
        while True:
          try:
            file = self.filelist.pop()
          except IndexError as e:
            break
          else:
            self.funname(file)
      threads = []
      while threads or self.filelist:
        for thread in threads:
          if not thread.is_alive():
            threads.remove(thread)
        while len(threads) < self.max_threads and self.filelist:
          thread = threading.Thread(target = runs)
          thread.setDaemon(True)
          thread.start()
          threads.append(thread)
  class Mymultiprocessing (MyTMultithread):
  '''''
  多进程运行函数,多进程多线程运行函数
  args:
    filelist  函数的参数为列表格式,
    funname  函数的名字为字符串,函数仅有一个参数为file
    delay   每个线程\进程之间的延迟,
    max_threads 最大的线程数
    max_multiprocess 最大的进程数
  '''
    def __init__(self,filelist,delay,funname,max_multiprocess = 1,max_threads = 1):
      self.funname = funname
      self.filelist = filelist[:]
      self.delay = delay
      self.max_threads = max_threads
      self.max_multiprocess = max_multiprocess
      self.num_cpus = multiprocessing.cpu_count()
    def multiprocessingOnly(self):
      '''''
    只使用多进程
      '''
      num_process = min(self.num_cpus,self.max_multiprocess)
      processes = []
      while processes or self.filelist:
        for p in processes:
          if not p.is_alive():
            # print(p.pid,p.name,len(self.filelist))
            processes.remove(p)
        while len(processes) < num_process and self.filelist:
          try:
            file = self.filelist.pop()
          except IndexError as e:
            break
          else:
            p = multiprocessing.Process(target=self.funname,args=(file,))
            p.start()
            processes.append(p)
    def multiprocessingThreads(self):
      num_process = min(self.num_cpus,self.max_multiprocess)
      p = Pool(num_process)
      DATALISTS = []
      tempmod = len(self.filelist) % (num_process)
      CD = int((len(self.filelist) + 1 + tempmod)/ (num_process))
      for i in range(num_process):
        if i == num_process:
          DATALISTS.append(self.filelist[i*CD:-1])
        DATALISTS.append(self.filelist[(i*CD):((i+1)*CD)])
      try:
        processes = []
        for i in range(num_process):
          #print('wait add process:',i+1,time.clock())
          #print(eval(self.funname),DATALISTS[i])
          MultThread = MyTMultithread(DATALISTS[i],self.delay,self.funname,self.max_threads)
          p = multiprocessing.Process(target=MultThread.startrun())
          #print('pid & name:',p.pid,p.name)
          processes.append(p)
        for p in processes:
          print('wait join ')
          p.start()
        print('waite over')
      except Exception as e:
        print('error :',e)
      print ('end process')
  def func1(file):
    print(file)
  if __name__ == '__main__':
    a = list(range(0,97))
    '''''
    测试使用5线程
    '''
    st = time.clock()
    asc = MyTMultithread(a,0,'func1',5)
    asc.startrun()
    end = time.clock()
    print('*'*50)
    print('多线程使用时间:',end-st)
    #测试使用5个进程
    st = time.clock()
    asd = Mymultiprocessing(a,0,'func1',5)
    asd.multiprocessingOnly()
    end = time.clock()
    print('*'*50)
    print('多进程使用时间:',end-st)
    #测试使用5进程10线程
    st = time.clock()
    multiPT = Mymultiprocessing(a,0,'func1',5,10)
    multiPT.multiprocessingThreads()
    end = time.clock()
    print('*'*50)
    print('多进程多线程使用时间:',end-st)

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python的for和break循环结构中使用else语句的技巧
May 24 Python
Linux下python与C++使用dlib实现人脸检测
Jun 29 Python
tensorflow实现逻辑回归模型
Sep 08 Python
python初学者,用python实现基本的学生管理系统(python3)代码实例
Apr 10 Python
python excel转换csv代码实例
Aug 26 Python
python脚本之一键移动自定格式文件方法实例
Sep 02 Python
python 实现多维数组转向量
Nov 30 Python
Django表单提交后实现获取相同name的不同value值
May 14 Python
python2和python3哪个使用率高
Jun 23 Python
如何设置PyCharm中的Python代码模版(推荐)
Nov 20 Python
python爬虫中抓取指数的实例讲解
Dec 01 Python
Linux系统下升级pip的完整步骤
Jan 31 Python
python爬取各类文档方法归类汇总
Mar 22 #Python
关于Python正则表达式 findall函数问题详解
Mar 22 #Python
Django自定义过滤器定义与用法示例
Mar 22 #Python
Python实现基于TCP UDP协议的IPv4 IPv6模式客户端和服务端功能示例
Mar 22 #Python
Python cookbook(数据结构与算法)将名称映射到序列元素中的方法
Mar 22 #Python
Python cookbook(数据结构与算法)从字典中提取子集的方法示例
Mar 22 #Python
python实现将excel文件转化成CSV格式
Mar 22 #Python
You might like
十大感人催泪爱情动漫 第一名至今不忍在看第二遍
2020/03/04 日漫
PHP脚本的10个技巧(5)
2006/10/09 PHP
PHP has encountered a Stack overflow问题解决方法
2014/11/03 PHP
php文件上传简单实现方法
2015/01/24 PHP
CodeIgniter钩子用法实例详解
2016/01/20 PHP
php引用和拷贝的区别知识点总结
2019/09/23 PHP
js比较和逻辑运算符的介绍
2013/03/10 Javascript
Javascript页面跳转常见实现方式汇总
2015/11/28 Javascript
javascript每日必学之多态
2016/02/23 Javascript
jquery实现左右无缝轮播图
2020/07/31 Javascript
利用策略模式与装饰模式扩展JavaScript表单验证功能
2017/02/14 Javascript
jQuery实现获取table中鼠标click点击位置行号与列号的方法
2017/10/09 jQuery
JS简单实现数组去重的方法分析
2017/10/14 Javascript
vue axios 给生产环境和发布环境配置不同的接口地址(推荐)
2018/05/08 Javascript
基于JS实现带动画效果的流程进度条
2018/06/01 Javascript
JavaScript中变量提升与函数提升经典实例分析
2018/07/26 Javascript
使用pkg打包Node.js应用的方法步骤
2018/10/19 Javascript
浅谈ng-zorro使用心得
2018/12/03 Javascript
vue-amap根据地址回显地图并mark的操作
2020/11/03 Javascript
Python3.x和Python2.x的区别介绍
2013/02/12 Python
python实现将英文单词表示的数字转换成阿拉伯数字的方法
2015/07/02 Python
深入理解python中的浅拷贝和深拷贝
2016/05/30 Python
使用python遍历指定城市的一周气温
2017/03/31 Python
Python初学时购物车程序练习实例(推荐)
2017/08/08 Python
详解Python在七牛云平台的应用(一)
2017/12/05 Python
Python实现感知器模型、两层神经网络
2017/12/19 Python
Python unittest单元测试框架总结
2018/09/08 Python
Anaconda+VSCode配置tensorflow开发环境的教程详解
2020/03/30 Python
用Python 执行cmd命令
2020/12/18 Python
Willer台湾:日本高速巴士/夜行巴士预约
2017/07/09 全球购物
波兰珠宝品牌:YES
2019/08/09 全球购物
《蚕姑娘》教学反思
2014/04/15 职场文书
师德师风个人反思
2014/04/28 职场文书
辞职信标准格式
2015/02/27 职场文书
浅谈JavaScript浅拷贝和深拷贝
2021/11/07 Javascript
关于SpringBoot 使用 Redis 分布式锁解决并发问题
2021/11/17 Redis