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开发之字符串string操作方法实例详解
Nov 12 Python
python+tkinter编写电脑桌面放大镜程序实例代码
Jan 16 Python
tensorflow输出权重值和偏差的方法
Feb 10 Python
python使用turtle库绘制树
Jun 25 Python
Django数据库连接丢失问题的解决方法
Dec 29 Python
Python切片操作去除字符串首尾的空格
Apr 22 Python
用Python从0开始实现一个中文拼音输入法的思路详解
Jul 20 Python
Django框架models使用group by详解
Mar 11 Python
python由已知数组快速生成新数组的方法
Apr 08 Python
Python爬虫抓取论坛关键字过程解析
Oct 19 Python
python中@property的作用和getter setter的解释
Dec 22 Python
python爬虫线程池案例详解(梨视频短视频爬取)
Feb 20 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编程每天必学之表单验证
2016/03/01 PHP
php处理抢购类功能的高并发请求
2018/02/08 PHP
tp5递归 无限级分类详解
2019/10/18 PHP
读JavaScript DOM编程艺术笔记
2011/11/15 Javascript
laydate 显示结束时间不小于开始时间的实例
2017/08/11 Javascript
Cpage.js给组件绑定事件的实现代码
2017/08/31 Javascript
Vue.js与 ASP.NET Core 服务端渲染功能整合
2017/11/16 Javascript
Python中捕捉详细异常信息的代码示例
2014/09/18 Python
python中xrange用法分析
2015/04/15 Python
python获取本机外网ip的方法
2015/04/15 Python
利用Python破解验证码实例详解
2016/12/08 Python
python中快速进行多个字符替换的方法小结
2016/12/15 Python
pycharm下打开、执行并调试scrapy爬虫程序的方法
2017/11/29 Python
Python将多个excel表格合并为一个表格
2021/02/22 Python
python写入已存在的excel数据实例
2018/05/03 Python
django中静态文件配置static的方法
2018/05/20 Python
使用pyinstaller打包PyQt4程序遇到的问题及解决方法
2019/06/24 Python
对Python函数设计规范详解
2019/07/19 Python
Python中list的交、并、差集获取方法示例
2019/08/01 Python
利用Python复制文件的9种方法总结
2019/09/02 Python
详解python程序中的多任务
2020/09/16 Python
canvas像素点操作之视频绿幕抠图
2018/09/11 HTML / CSS
波兰电子产品购物网站:Vobis
2019/05/26 全球购物
Arti-shopping中文官网:大型海外商品一站式直邮平台
2020/03/23 全球购物
C/C++有关内存的思考题
2015/12/04 面试题
Java文件和目录(IO)操作
2014/08/26 面试题
办公室主任岗位职责
2013/11/08 职场文书
大学生表扬信范文
2014/01/09 职场文书
2014年元旦促销活动方案
2014/02/22 职场文书
优秀家长自荐材料
2014/08/26 职场文书
房产授权委托书范本
2014/09/22 职场文书
2014矛盾纠纷排查调处工作总结
2014/12/09 职场文书
2016寒假社会实践心得体会范文
2015/10/09 职场文书
创业计划书之餐饮馄饨店
2019/07/18 职场文书
使用vuex-persistedstate本地存储vuex
2022/04/29 Vue.js
Nginx如何获取自定义请求header头和URL参数详解
2022/07/23 Servers