• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-07) 34次浏览 已收录 0个评论

这篇文章主要介绍了Python实现的自定义多线程多进程类,结合实例形式分析了Python多线程多进程的相关调用与使用操作技巧,需要的朋友可以参考下

本文实例讲述了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_multipro来源gao.dai.ma.com搞@代*码网cess) 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) 

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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

以上就是Python实现的自定义多线程多进程类示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python实现的自定义多线程多进程类示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址