Python实现的自定义多线程多进程类示例
作者:Magicapprentice 发布时间:2023-11-16 08:52:15
标签: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_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
0
投稿
猜你喜欢
- 现在网页设计师除了把页面做的漂亮以外,越来越注重“用户体验”,就是要做“别让用户思考”的网页,使网站真正做到“可用性”。望望结合几年的工作经
- 代码如下: var params = new Enumerator(Request.QueryString); while (!params
- 看了一个月的文档和资料以后,终于让我参与到项目中来了,哈哈,痛快!虽然只是让我解决一个小问题,不过有活干就是好。在写代码的过程中遇到了一个小
- <div id="outer" style="background:#099"> cli
- 最近在用fso,读取txt文本文件的内容时碰到了“输入超出了文件尾 ”的运行错误,当txt中的内容为空的时候就出现这个问题了,查了
- python如何跳过异常继续执行下面有两种解决方法第一种是类似if…else…;另外一种是使用语
- PyType_Type和PyBaseObject_TypePyObject和PyTypeObject内容的最后指出下图中对实例对象和类型对象
- :hover是我们在CSS设计中最常运用的伪类之一,许多绚丽效果的实现离不开伪类:hover,比如我们常见的纯CSS菜单、相册效果等等。或许
- <%@ Language=VBScript %><%Option Explicit %><%Dim strUR
- 回调函数用起来比较爽。特别是在js中,满世界全是回调,那么在python中,怎么来优雅地实现自己的回调函数呢下面贴一个我写的例子class
- 本文实例讲述了Python按行读取文件的实现方法。分享给大家供大家参考,具体如下:小文件:#coding=utf-8#author: wal
- 本文实例讲述了PHP判断是否微信访问的方法。分享给大家供大家参考,具体如下:在开发中有时需要禁止或者仅允许微信浏览器进行访问,则此时就需要对
- kNN(k-nearest neighbor)是一种基本的分类与回归的算法。这里我们先只讨论分类中的kNN算法。k邻近算法的输入为实例的特征
- 尽管某些书籍上总是说避免使用全局变量,但是在实际的需求不断变化中,往往定义一个全局变量是最可靠的方法,但是又必须要避免变量名覆盖。Pytho
- 问题:1.一个销售系统,设有各级代理商,每个代理商的表是这样设计的 数据库结构表1: 代理商资料表[id]
- 最近关于浏览器的最重要的事情就是IE的极光0day漏洞了,这个漏洞导致包括Google在内的多家美国公司受到黑客的攻击,当然也有很多网站被黑
- 一、使用 reflect.Type 创建实例在通过 reflect.TypeOf 函数获取到变量的反射类型对象之后,可以通过反射类型对象 r
- 使用MySQL,安全问题不能不注意。以下是MySQL提示的23个注意事项:1.如果客户端和服务器端的连接需要跨越并通过不可信任的网络,那么就
- 这是解释器设置问题,在设置里找到interpreter 找到合适的目录就可以了。因为重装了python导致pycharm找不到路径了。另外,
- IE在处理透明度上真够恶心,而且在IE7必须让元素的hasLayout为ture,要不会失效。以下是我最新处理透明度的代码:var