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

作者:Magicapprentice 时间:2023-11-16 08:52:15 

本文实例讲述了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程序设计有所帮助。

来源:https://blog.csdn.net/Magicapprentice/article/details/71597475

标签:Python,多线程,多进程
0
投稿

猜你喜欢

  • javaScript事件机制兼容【详细整理】

    2024-05-13 10:07:01
  • python爬虫 爬取超清壁纸代码实例

    2021-03-19 02:51:54
  • 使用SQL批量替换语句修改、增加、删除字段内容

    2024-01-21 16:52:39
  • python代码的几种常见加密方式分享

    2021-05-19 02:14:56
  • 视觉对交互的帮助——提升可用性

    2008-10-16 13:16:00
  • Python+Opencv实现表格边框线检测

    2023-08-11 04:55:14
  • Python绘制词云图之可视化神器pyecharts的方法

    2022-12-08 14:38:44
  • Vue Socket.io源码解读

    2024-06-05 15:28:35
  • Django 设置多环境配置文件载入问题

    2023-09-08 09:16:19
  • JS的IE和FF兼容性问题汇总

    2008-03-08 13:01:00
  • 安装sql server 2008时的4个常见错误和解决方法

    2024-01-22 10:24:58
  • php中debug_backtrace、debug_print_backtrace和匿名函数用法实例

    2023-06-11 23:08:24
  • 灵活调用xsl来解析xml文档(js异步)

    2008-09-05 17:12:00
  • 深度学习入门之Pytorch 数据增强的实现

    2021-04-05 22:26:07
  • 网页开发中的容易忽略的问题 javascript HTML中的table

    2023-09-04 20:43:52
  • Python的Django框架中从url中捕捉文本的方法

    2023-08-29 11:13:13
  • 利用WSH获取计算机硬件信息、DNS信息等

    2008-05-05 13:04:00
  • Python使用matplotlib实现的图像读取、切割裁剪功能示例

    2021-12-14 11:04:49
  • python中字典增加和删除使用方法

    2023-12-15 15:31:30
  • python和C++共享内存传输图像的示例

    2021-03-28 01:27:57
  • asp之家 网络编程 m.aspxhome.com