当前位置:网站首页>多线程和并发编程(二)
多线程和并发编程(二)
2022-07-06 07:08:00 【And ν】
目录
多线程和并发编程(二)
进程的创建-Proccess子类
创建进程的方式还可以使用类的方式,可以自定义-一个类,继承Process类,每次实例化这个类的时候,就等同于实例化一个进程对象。
[示例]继承Process的类,重写run0方法创建进程
# 导入模块
from multiprocessing import Process
from time import sleep
import time
# 定义类
class ClockProcess(Process):
# 重新初始化方法
def __init__(self,interval):
Process.__init__(self)
self.interval=interval
def run(self):
# 创建子进程
print("子进程开始执行的时间:{}".format(time.ctime()))
sleep(self.interval)
print("子进程执行结束时间:{}".format(time.ctime()))
if __name__ =="__main__":
p=ClockProcess(4)
p.start()
p.join()
print("主进程结束")
进程池
在利用Python进行系统管理的时候,特别是同时操作多个文件目录,或者远程控制多台主机,并行操作可以节约大量的时间。当被操作对象数目不大时,可以直接利用multiprocessing中的Process动态成生多个进程,十几个还好,但如果是上百个,上千个目标,手动的去限制进程数量却又太过繁琐,此时可以发挥进程池的功效。
Pool可以提供指定数量的进程,供用户调用,当有新的请求提交到pool中时,如果池还没有满,那么就会创建-一个新的进程 用来执行该请求;但如果池中的进程数己经达到规定最大值,那么该请求就会等待,直到池中有进程结束,才会创建新的进程。Pool 的语法格式如下:
Pool ([numprocess [ initializer [, initrg]])
其中numprocess是要创建的进程数。如果省略此参数,将使用cpu _count()的值.Initializer是每个工作进程启动时要执行的可调用对象。Initargs 是要传递给initializer的参数元祖。Initializer默认为None.
Pool实例方法表
方法 | 描述 |
---|---|
apply (fune [, args, [, kwargs]]) | 在一个池工作进程中执行函数(*arss, **kwares), 然后返回结果。 |
apply_async(func,[,args[,kwargs[,callback]]]) | 在 一个池工作进程中异步地执行函数(*arss, **kwarss),然后返回结果。此方法的结果是AsyncResult类的实例,稍后可用于获得最终结果。Callback 是可调用对象,接受输入参数。当func的结果变为可用时,将立即传递给callback. Callback 禁止执行任何阻塞操作,否则将阻塞接收其他异步操作中的结果。 |
close() | 关闭进程池,防止进行进- -步操作。 如果还有挂起的操作,它们将在工作进程终止之前完成 |
join() | 等待所有工作进程退出。此方法只能在close () 或者terminate ()方法之后调用 |
imap( func, iterable [,chunksize] ) | map ()函数的版本之一,返回迭代器而非结果列表 |
imap unordered( fune. ,iterable [ ,chunksize] ) | 同 imap()函数一样,只是结果的顺序根据从工作进程接收到的时间任意确定 |
map( func, iterable [,chunksize] ) | 将可调用对象fune应用给iterable.中的所有项,然后以列表的形式返回结果。通过将iterable划分为多块并将工作分派给工作进程,可以并行地执行这项操作。chunksize.指定每块中的项数。如果数量较大,可以增大chunksize.的值来提升性能 |
map_ asyne( fune, iterable[, chunksize[,callback]] ) | 同 map ()函数,但结果的返回是异步的。返回值是AsyncResult 类的实例,稍后可用与获取结果。Callback是指接受一个参数的可调对象。如果提供callable,当结果变为可用时,将使用结果调用callable。 |
terminate() | 即终止所有工作进程,同时不执行任何清理或结束任何挂起工作。如果p被垃圾回收,将自动调用此函数。 |
get( [ timeout] ) | 返回结果,如果有必要则等待结果到达。Timeout 是可选的超时。如果结果在指定时间内没有到达,将引发multiprocessing. TimeoutError异常。如果远程操作中引发了异常,它将在调用此方法时再次被引发 |
ready() | 如果调用完成,则返回True |
sucessful() | 如果调用完成且没有引发异常,返回True.如果在结果就绪之前调用此方法,将引发AssertionError异常 |
wait( [timeout] ) | 等待结果变为可用。Timeout是可选的超时 |
注意:
apply_ async(func[, args[, kwds[, callback]])它是非阻塞,apply(func[, args[, kwds])是阻塞的
[示例]进程池的使用(非阻塞)
# 导入模块
import multiprocessing
import time
# 进程执行的任务函数
def func(msg):
print('start',msg)
time.sleep(3)
print('end',msg)
if __name__=='__main__':
# 创建初始化3的进程池
pool=multiprocessing.Pool(3)
# 添加任务
for i in range(1,6):
msg='任务%d'%i
pool.apply_async(func,(msg,))
# 若进程不再接收新的请求 调用close
pool.close()
# 等待子进程结束
pool.join()
边栏推荐
- Applied stochastic process 01: basic concepts of stochastic process
- Embed UE4 program into QT interface display
- 《从0到1:CTFer成长之路》书籍配套题目(周更)
- Lesson 12 study notes 2022.02.11
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- NFT on fingertips | evaluate ambire on G2, and have the opportunity to obtain limited edition collections
- UWA pipeline version 2.2.1 update instructions
- 数据仓库建设思维导图
- LeetCode Algorithm 2181. 合并零之间的节点
- Is software testing outsourcing going or not? Three years' real outsourcing experience tells you
猜你喜欢
医疗软件检测机构怎么找,一航软件测评是专家
Cif10 actual combat (resnet18)
leetcode1020. Number of enclaves (medium)
OpenGL ES 学习初识(1)
Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
leetcode6109. 知道秘密的人数(中等,周赛)
How to reconstruct the class explosion caused by m*n strategies?
CDN acceleration and cracking anti-theft chain function
leetcode704. Binary search (find an element, simple, different writing)
What is the biggest problem that fresh e-commerce is difficult to do now
随机推荐
LeetCode Algorithm 2181. 合并零之间的节点
PCL实现选框裁剪点云
The difference between get and post request types
《从0到1:CTFer成长之路》书籍配套题目(周更)
Pymongo gets a list of data
WPF之MVVM
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
UWA pipeline version 2.2.1 update instructions
UWA Pipeline 2.2.1 版本更新说明
Proteus -- Serial Communication parity flag mode
What is the biggest problem that fresh e-commerce is difficult to do now
After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.
hydra常用命令
软件测试外包到底要不要去?三年真实外包感受告诉你
Is software testing outsourcing going or not? Three years' real outsourcing experience tells you
Path analysis model
JDBC学习笔记
MPLS experiment
Internal and external troubles of "boring ape" bayc
Cookie Technology & session Technology & ServletContext object