python multiprocessing模块
python multiprocessing模块
multiprocessing
multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
创建进程的类:Process([group[, target[, name[, args[, kwargs]]]]])
target表示调用对象
args表示调用对象的位置参数元组。
kwargs表示调用对象的字典。name为别名。
group表示线程组。 方法:
is_alive():返回进程是否
join([timeout])运行:阻塞当前上下文环境的进程,直到调用此方法的进程终止或到达指定timeout(可选参数)
run():start()调用run方法,如果实例进程时未制定target,这start执行 默认run()方法
start():进程准备就绪,等待CPU调度
terminate():不管任务是否完成,立即停止工作进程
其中,Process以start()启动某个进程。 属性:authkey、daemon(要通过start()
设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()
之前设置。
Process类
构造方法: Process([group [, target [, name [, args [, kwargs]]]]]) group: 线程组,目前还没有实现,库引用中提示必须是None;
target: 要执行的方法;
name: 进程名;
args/kwargs: 要传入方法的参数。 实例方法: is_alive():返回进程是否在运行。 join([timeout]):阻塞当前上下文环境的进程程,直到调用此方法的进程终止或到达指定的timeout(可选参数)。 start():进程准备就绪,等待CPU调度 run():strat()调用run方法,如果实例进程时未制定传入target,这star执行t默认run()方法。 terminate():不管任务是否完成,立即停止工作进程 属性: daemon:和线程的setDeamon功能一样 name:进程名字。 pid:进程号。
进程的调用
关于创建多线程
四种方法可以创建多线程
(1)系统初始化:启动操作系统时开启的线程,比如前后台进程。
(2)执行了正在运行的进程所调用的进程创建系统进程:一个正在运行的进程经常发出系统调用,以便创建一个或多个新进程协助其工作。
(3)用户请求创建一个新进程:双击图标,打开一个新程序,又比如运行我们编写的程序等。
(4)一个批处理作业的初始化:这种只有在大型机的批处理系统中应用,在这里不提及。
注意:所有情形中,新进程都是由一个已存在的进程执行一个用于创建进程的系统调用而创建的,这个进程所做的工作是,执行一个用来创建新进程的系统调用,系统调用会通知操作系统创建一个新进程,并且直接或间接地指定在该进程中运行的程序。 UNIX:fork,这个系统调用会创建一个与调用进程相同的副本,父进程与子进程拥有相同的存储映像,通常,子进程接着执行execve或一个类似的系统调用,以修改其存储映像并运行一个新的程序。
Windows:Win32函数调用Create'Process创建进程,也负责进行父子进程的复制,该调用由10个参数。
UNIX、Windows中,进程创建之后,父子进程有各自不同的地址,如果其中某个进程在其地址空间进行修改(可写内存),这个修改对于其他进程而言是不可见的。(不共享内存)
UNIX,子进程的初始地址是父进程的副本,但这里涉及两个不同的地址看见,不可写的内存是共享的(某些UXIX的实现使程序正文在两者共享,因为它不能被修改),对于新创建的进程而言,有可能共享其创建者的其他资源,比如打开的文件等。
Windows中,从一开始父进程与子进程的地址空间就不一样。
#创建调用多进程
#函数
# import multiprocessing
# import time
#
# def worker_1(interval):
# print("worker_1")
# time.sleep(interval)
# print("end worker_1")
#
# def worker_2(interval):
# print("worker_2")
# time.sleep(interval)
# print("end worker_2")
#
#
# if __name__ == "__main__":
# p1 = multiprocessing.Process(target = worker_1, args = (2,))
# p2 = multiprocessing.Process(target = worker_2, args = (3,))
# p1.start()
# p2.start()
# p1.join()
# p2.join()
# print('finsh end') #定义成类
# import multiprocessing
# import time
#
# class ClockProcess(multiprocessing.Process):
# def __init__(self, interval):
# multiprocessing.Process.__init__(self)
# self.interval = interval
#
# def run(self):
# n = 5
# while n > 0:
# print("the time is {0}".format(time.ctime()))
# time.sleep(self.interval)
# n -= 1
#
# if __name__ == '__main__':
# p = ClockProcess(3)
# p.start()
进程同步
注意:这里使用锁需要把锁传递进函数,因为是使用的是不同的进程,这里有复制拷贝!!!
from multiprocessing import Process, Lock
def f(l, i):
with l.acquire():
print('hello world %s'%i)
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()
进程间通讯
进程对列Queue
from multiprocessing import Process, Queue
import queue def f(q,n):
#q.put([123, 456, 'hello'])
q.put(n*n+1)
print("son process",id(q)) if __name__ == '__main__':
q = Queue() #try: q=queue.Queue()
print("main process",id(q)) for i in range(3):
p = Process(target=f, args=(q,i))
p.start() print(q.get())
print(q.get())
print(q.get())
管道
The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way). For example:

from multiprocessing import Process, Pipe def f(conn):
conn.send([12, {"name":"yuan"}, 'hello'])
response=conn.recv()
print("response",response)
conn.close()
print("q_ID2:",id(child_conn)) if __name__ == '__main__': parent_conn, child_conn = Pipe()
print("q_ID1:",id(child_conn))
p = Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv()) # prints "[42, None, 'hello']"
parent_conn.send("儿子你好!")
p.join()
The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv() methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.
Managers
Queue和pipe只是实现了数据交互,并没实现数据共享,即一个进程去更改另一个进程的数据。
A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Barrier, Queue, Value and Array. For example:

from multiprocessing import Process, Manager def f(d, l,n):
d[n] = '1'
d['2'] = 2
d[0.25] = None
l.append(n)
#print(l) print("son process:",id(d),id(l)) if __name__ == '__main__': with Manager() as manager: d = manager.dict() l = manager.list(range(5)) print("main process:",id(d),id(l)) p_list = [] for i in range(10):
p = Process(target=f, args=(d,l,i))
p.start()
p_list.append(p) for res in p_list:
res.join() print(d)
print(l)

进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
- apply
- apply_async

from multiprocessing import Process,Pool
import time,os def Foo(i):
time.sleep(1)
print(i)
return i+100 def Bar(arg): print(os.getpid())
print(os.getppid())
print('logger:',arg) pool = Pool(5) Bar(1)
print("----------------") for i in range(10):
#pool.apply(func=Foo, args=(i,))
#pool.apply_async(func=Foo, args=(i,))
pool.apply_async(func=Foo, args=(i,),callback=Bar) pool.close()
pool.join()
print('end')

python multiprocessing模块的更多相关文章
- python MultiProcessing模块进程间通信的解惑与回顾
这段时间沉迷MultiProcessing模块不能自拔,没办法,python的基础不太熟,因此就是在不断地遇到问题解决问题.之前学习asyncio模块学的一知半解,后来想起MultiProcessin ...
- python multiprocessing模块 介绍
一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_count\(\)查看),在python中大部分情况需要使用多进 ...
- Python multiprocessing模块的Pool类来代表进程池对象
#-*-coding:utf-8-*- '''multiprocessing模块提供了一个Pool类来代表进程池对象 1.Pool可以提供指定数量的进程供用户调用,默认大小是CPU的核心数: 2.当有 ...
- Python标准模块--multiprocessing
1 模块简介 multiprocessing模块在Python2.6中引入.最初的multiprocessing是由Jesse Noller和Richard Oudkerk在PEP 371中定义.就像 ...
- Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块
Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fab ...
- python多进程multiprocessing模块中Queue的妙用
最近的部门RPA项目中,小爬为了提升爬虫性能,使用了Python中的多进程(multiprocessing)技术,里面需要用到进程锁Lock,用到进程池Pool,同时利用map方法一次构造多个proc ...
- Python之进程 2 - multiprocessing模块
我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起来的python程序也是一个进程,那么我们也可以在程序中再创建进程.多个进程可以实现并发效果,也就是说, ...
- python之多进程multiprocessing模块
process类介绍 multiprocessing 模块官方说明文档 Process 类用来描述一个进程对象.创建子进程的时候,只需要传入一个执行函数和函数的参数即可完成 Process 示例的创建 ...
- python 3 并发编程之多进程 multiprocessing模块
一 .multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程. ...
随机推荐
- 2018-2019-2 20165235《网络对抗技术》Exp8 Web基础
2018-2019-2 20165235<网络对抗技术>Exp8 Web基础 实践过程记录: (1).Web前端HTML 能正常安装.启停Apache.理解HTML,理解表单,理解GET与 ...
- 惠普服务器DL360G6安装ESXi主机后遗忘密码用u盘重置密码
惠普服务器DL360G6安装ESXi主机后遗忘密码重置密码 先用rufus制作U盘启动盘,启动盘一定要用惠普专用hpe的esxi版本,否则安装会报错, 下载https://www.iplaysoft. ...
- 在windows下使用Mingw搭建模拟Linux
1.到官网下载最新版Mingw 2.点击安装,最好选择默认路径,如果不是的话,路径中一定不能有空格. 3.选择安装,mingw-developer-toolkit.mingw32-base.mingw ...
- WCF 配置说明
关于WCF中的地址和绑定,需要补充一下. WCF中支持的传输协议包括HTTP.TCP.Peer network(对等网).IPC(基于命名管道的内部进程通信)以及MSMQ(微软消息队列),每个协议对应 ...
- 阶段2 JavaWeb+黑马旅游网_15-Maven基础_第4节 maven生命周期和概念模型图_09maven概念模型图
项目自身的信息 项目运行所依赖的扎包 运行环境信息:tomcat啊,JDK啊这些都属于运行环境 一个jar包的坐标由三个最基本的信息组成. 第一部分就是依赖管理. 第二个部分
- 前后端分离&接口API设计学习报告
接口API设计学习报告 15331023 陈康怡 什么是API? API即Application Programming Interface.API是一种通道,负责一个程序与另一个程序的沟通.而对于w ...
- css让字体细长
transform: scale(1,3); -ms-transform: scale(1,3); -webkit-transform: scale(1,3); -moz-transform: sca ...
- JVM监控工具之JVisualVM
一.简介 JVisualVM是Netbeans的profile子项目,已在JDK6.0 update 7 中自带(bin/jvisualvm.exe),能够监控线程,内存情况,查看方法的CPU时间和内 ...
- 4.1.k8s.svc(Service)
#Service Service为Pod提供4层负载均衡, 访问 -> Service -> Pod组 #4种类型 ClusterIP 默认,分配一个VIP,只能内部访问 NodePort ...
- 【MM系列】SAP MM模块-如何修改物料的移动平均价
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP MM模块-如何修改物料的移动 ...