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

  介绍

这篇文章主要介绍了Python如何实现的自定义多线程多进程类示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。

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

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

# !/usr/bin/env  Python   #,才能- *安康;编码:utf-8  - * -   #,才能@Time ,: 2017/5/10  47   #,才能@Author : zhaowen.zhu   #,才能@Site ,:   #,才能@File ,: MultiThread.py   #,才能@Software: Python 闲置   import 才能线程、时间、多处理系统   得到才能multiprocessing  import 池   class 才能MyTMultithread (threading.Thread):   ,,,& # 39;& # 39;& # 39;& # 39;& # 39;   ,,,自定义的线程函数,   ,,,功能:使用多线程运行函数,函数的参数只有一个文件,并且未实现结果值的返回   ,,,arg游戏:   ,,,,,filelist ,函数的参数为列表格式,   ,,,,,funname ,函数的名字为字符串,函数仅有一个参数为文件   ,,,,,delay ,,每个线程之间的延迟,   ,,,,,max_threads 线程的最大值   ,,,& # 39;& # 39;& # 39;   ,,,def  __init__(自我,文件列表,延迟,funname max_threads =, 50):   ,,,,,threading.Thread.__init__(自我)   ,,,,,self.funname =funname   ,,,,,self.filelist =,文件列表[:]   ,,,,,self.delay =延迟   ,,,,,self.max_threads =max_threads   ,,,def  startrun(自我):   ,,,,,def 运行():   ,,,,,,,time . sleep (self.delay)   ,,,,,,,while 正确的:   ,,,,,,,,,试一试:   ,,,,,,,,,,,file =, self.filelist.pop ()   ,,,,,,,,,except  IndexError  as  e:   ,,,,,,,,,,,休息   ,,,,,,,,,其他的:   ,,,,,,,,,,,self.funname(文件)   ,,,,,threads =, []   ,,,,,while  threads 或是self.filelist:   ,,,,,,,for  thread 拷贝线程:   ,,,,,,,,,if  not  thread.is_alive ():   ,,,,,,,,,,,threads.remove(线程)   ,,,,,,,while  len(线程),& lt;, self.max_threads 以及self.filelist:   ,,,,,,,,,thread =, threading.Thread (=target 运行)   ,,,,,,,,,thread.setDaemon(真正的)   ,,,,,,,,,thread.start ()   ,,,,,,,,,threads.append(线程)   class 才能;Mymultiprocessing  (MyTMultithread):   & # 39;才能& # 39;& # 39;& # 39;& # 39;   多才能进程运行函数,多进程多线程运行函数   args才能:   ,,,filelist ,函数的参数为列表格式,   ,,,funname ,函数的名字为字符串,函数仅有一个参数为文件   ,,,delay ,,每个线程\进程之间的延迟,   ,,,max_threads 最大的线程数   ,,,max_multiprocess 最大的进程数   & # 39;才能& # 39;& # 39;   ,,,def  __init__(自我,文件列表,延迟,funname max_multiprocess =, 1, max_threads =, 1):   ,,,,,self.funname =funname   ,,,,,self.filelist =,文件列表[:]   ,,,,,self.delay =延迟   ,,,,,self.max_threads =max_threads   ,,,,,self.max_multiprocess =max_multiprocess   ,,,,,self.num_cpus =, multiprocessing.cpu_count ()   ,,,def  multiprocessingOnly(自我):   ,,,,,& # 39;& # 39;& # 39;& # 39;& # 39;   ,,,只使用多进程   ,,,,,& # 39;& # 39;& # 39;   ,,,,,num_process =, min (self.num_cpus self.max_multiprocess)   ,,,,,processes =, []   ,,,,,while  processes 或是self.filelist:   ,,,,,,,for  p 拷贝过程:   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

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