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处理JSON时的值报错及编码报错的两则解决实录
Jun 26 Python
Python中Threading用法详解
Dec 27 Python
Python将多个excel文件合并为一个文件
Jan 03 Python
Python处理菜单消息操作示例【基于win32ui模块】
May 09 Python
Django实现分页功能
Jul 02 Python
利用python-pypcap抓取带VLAN标签的数据包方法
Jul 23 Python
python实现各种插值法(数值分析)
Jul 30 Python
Python中list循环遍历删除数据的正确方法
Sep 02 Python
pytorch实现用CNN和LSTM对文本进行分类方式
Jan 08 Python
对Keras中predict()方法和predict_classes()方法的区别说明
Jun 09 Python
Python基础进阶之海量表情包多线程爬虫功能的实现
Dec 17 Python
解决pytorch 的state_dict()拷贝问题
Mar 03 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
PHP实现MVC开发得最简单的方法――模型
2007/04/10 PHP
php中opendir函数用法实例
2014/11/15 PHP
php使用wordwrap格式化文本段落的方法
2015/03/17 PHP
php通过排列组合实现1到9数字相加都等于20的方法
2015/08/03 PHP
php实现概率性随机抽奖代码
2016/01/02 PHP
javascript整除实现代码
2010/11/23 Javascript
JQuery入门——用映射方式绑定不同事件应用示例
2013/02/05 Javascript
为JS扩展Array.prototype.indexOf引发的问题及解决办法
2015/01/21 Javascript
JavaScript实现重置表单(reset)的方法
2015/04/02 Javascript
jQuery插件制作之全局函数用法实例
2015/06/01 Javascript
关于Vue.js一些问题和思考学习笔记(2)
2016/12/02 Javascript
AngularJS实现controller控制器间共享数据的方法示例
2017/10/30 Javascript
webpack项目调试以及独立打包配置文件的方法
2018/02/28 Javascript
vue自定义js图片碎片轮播图切换效果的实现代码
2019/04/28 Javascript
微信小程序实现点击卡片 翻转效果
2019/09/04 Javascript
JsonServer安装及启动过程图解
2020/02/28 Javascript
Python回调函数用法实例详解
2015/07/02 Python
Python连接数据库学习之DB-API详解
2017/02/07 Python
python3利用Dlib19.7实现人脸68个特征点标定
2018/02/26 Python
python实现七段数码管和倒计时效果
2019/11/23 Python
python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+JS)
2020/03/18 Python
Python使用pycharm导入pymysql教程
2020/09/16 Python
CSS3按钮鼠标悬浮实现光圈效果源码
2016/09/11 HTML / CSS
Html5之title吸顶功能
2018/06/04 HTML / CSS
英国历史最悠久的DJ设备供应商:DJ Finance、DJ Warehouse、The DJ Shop
2019/09/04 全球购物
德国滑雪和户外用品网上商店:XSPO
2019/10/30 全球购物
.net面试题
2015/12/22 面试题
后勤人员自我鉴定
2013/10/20 职场文书
端午节寄语2015
2015/03/23 职场文书
2015年行政助理工作总结
2015/04/30 职场文书
刑事上诉状(量刑过重)
2015/05/23 职场文书
《7的乘法口诀》教学反思
2016/02/18 职场文书
五年级语文教学反思
2016/03/03 职场文书
导游词之西湖雷峰塔
2019/09/18 职场文书
单身狗福利?Python爬取某婚恋网征婚数据
2021/06/03 Python
MySQL外键约束(FOREIGN KEY)案例讲解
2021/08/23 MySQL