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 listdictNamespaceLockRLockSemaphoreBoundedSemaphoreConditionEventBarrierQueueValue 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模块的更多相关文章

  1. python MultiProcessing模块进程间通信的解惑与回顾

    这段时间沉迷MultiProcessing模块不能自拔,没办法,python的基础不太熟,因此就是在不断地遇到问题解决问题.之前学习asyncio模块学的一知半解,后来想起MultiProcessin ...

  2. python multiprocessing模块 介绍

    一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_count\(\)查看),在python中大部分情况需要使用多进 ...

  3. Python multiprocessing模块的Pool类来代表进程池对象

    #-*-coding:utf-8-*- '''multiprocessing模块提供了一个Pool类来代表进程池对象 1.Pool可以提供指定数量的进程供用户调用,默认大小是CPU的核心数: 2.当有 ...

  4. Python标准模块--multiprocessing

    1 模块简介 multiprocessing模块在Python2.6中引入.最初的multiprocessing是由Jesse Noller和Richard Oudkerk在PEP 371中定义.就像 ...

  5. Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

    Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fab ...

  6. python多进程multiprocessing模块中Queue的妙用

    最近的部门RPA项目中,小爬为了提升爬虫性能,使用了Python中的多进程(multiprocessing)技术,里面需要用到进程锁Lock,用到进程池Pool,同时利用map方法一次构造多个proc ...

  7. Python之进程 2 - multiprocessing模块

    ​ 我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起来的python程序也是一个进程,那么我们也可以在程序中再创建进程.多个进程可以实现并发效果,也就是说, ...

  8. python之多进程multiprocessing模块

    process类介绍 multiprocessing 模块官方说明文档 Process 类用来描述一个进程对象.创建子进程的时候,只需要传入一个执行函数和函数的参数即可完成 Process 示例的创建 ...

  9. python 3 并发编程之多进程 multiprocessing模块

    一 .multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程. ...

随机推荐

  1. JMS学习二(简单的ActiveMQ实例)

    下载安装ActiveMQ服务,下载地址当然可以去官网下载 http://activemq.apache.org/download-archives.html ActiveMQ安装很简单,下载解压后到b ...

  2. eclipse代码自动补全设置

    1.说明 eclipse安装好了之后,在编辑框中输入某个英文字符,默认不自动弹出自动代码选择框,需要手动按下 Alt + / 或者输入的字符为 .  才弹出代码自动补全框.其实eclipse是可以设置 ...

  3. IntelliJ IDEA2018破解教程

    破解方法:下载破解补丁→修改配置文件→输入激活码→激活成功 由于JetBrains封杀,大部分激活服务器已经不能使用,使用下面的比较麻烦的方法也可以进行破解,但是有效期是到2100年(emmmm,也算 ...

  4. Linux驱动开发10——内核环形双向链表

    Linux内核环形双向链表本身不实现锁机制,需要驱动本身完成锁机制实现. 1.1.list_head结构体 #include <linux/list.h> struct list_head ...

  5. association实现懒加载分段级联查询

    这里讲的是人员和部门进行级联分布查询 1.首先在mybatis-config.xml里进行配置 <settings> <!--显示的指定每个我们需要更改的配置的值,即使他是默认的.防 ...

  6. JS数组方法的的返回值和是否改变该数组总结

    concat() 方法 concat() 方法用于连接两个或多个数组. 该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本. 返回值 返回一个新的数组.该数组是通过把所有 arrayX 参数添 ...

  7. babel-node 和 nodemon

    概述 今天我继续完善我做的用来 mock 前端数据的库:ym-mock. 我想要实现 2 个需求: 支持 es6,至少要能 import 吧. 修改了代码之后能自动热更新,不能我修改了服务器代码要手动 ...

  8. 三:flask-配置文件的两种方式

    项目中,配置的参数一般采用配置文件的形式,方便统一管理 第一种方式:模块的形式:使用app.config.from_object(config)的方式加载配置文件,此方式需要导入配置文件视为模块 第二 ...

  9. NFS服务和DHCP服务讲解

    1.NFS服务端概述 NFS,是Network File System的简写,即网络文件系统.网络文件系统是FreeBSD支持的文件系统中的一种,也被称为NFS: NFS允许一个系统在网络上与他人共享 ...

  10. Matlab 文件格式化/Matlab Source File Formattor

    由于需要使用到别人编写的Matlab代码文件,但是呢不同的人有不同的风格,有的写得就比较糟糕了. 为了更好地理解代码的内容,一个比较美观的代码会让人身心愉悦. 但是在网上并没有找到一个比较好的实现,此 ...