当前位置:网站首页>多线程和并发编程(二)
多线程和并发编程(二)
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()
边栏推荐
- 升级版手机检测微信工具小程序源码-支持多种流量主模式
- Kubernetes cluster builds ZABBIX monitoring platform
- 基于PyTorch和Fast RCNN快速实现目标识别
- 接口自动化测试框架:Pytest+Allure+Excel
- 开源的网易云音乐API项目都是怎么实现的?
- BIO模型实现多人聊天
- leetcode704. 二分查找(查找某个元素,简单,不同写法)
- 作者已死?AI正用艺术征服人类
- How are the open source Netease cloud music API projects implemented?
- leetcode1020. Number of enclaves (medium)
猜你喜欢
Uncaught typeerror: cannot red properties of undefined (reading 'beforeeach') solution
kubernetes集群搭建Zabbix监控平台
Prefix and array series
1091: two or three things in childhood (multi instance test)
A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
leetcode704. 二分查找(查找某个元素,简单,不同写法)
leetcode59. 螺旋矩阵 II(中等)
医疗软件检测机构怎么找,一航软件测评是专家
leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
Simple use of MySQL database: add, delete, modify and query
随机推荐
Path analysis model
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
Win10 64 bit Mitsubishi PLC software appears oleaut32 DLL access denied
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
《从0到1:CTFer成长之路》书籍配套题目(周更)
18.多级页表与快表
SEO学习的最好方式:搜索引擎
Short video, more and more boring?
Misc of BUU (update from time to time)
Zhongqing reading news
漏了监控:Zabbix对Eureka instance状态监控
Top test sharing: if you want to change careers, you must consider these issues clearly!
19.段页结合的实际内存管理
19. Actual memory management of segment page combination
PCL实现选框裁剪点云
How to find a medical software testing institution? First flight software evaluation is an expert
A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
将ue4程序嵌入qt界面显示
Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)
Attributeerror: can 't get attribute' sppf 'on < module' models. Common 'from' / home / yolov5 / Models / comm