multiprocessing
multiprocessing
multiprocessing模块是跨平台版本的多进程模块。
multiprocessing模块提供了一个Process类来代表一个进程对象。
multiprocessing模块提供了一个Pool类,可以提供指定数量的进程供用户调用。
Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。
一、Process类
multiprocessing模块提供了一个Process类来代表一个进程对象。
实例:
from multiprocessing import Process
import os # 子进程要执行的代码
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid())) if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('Child process end.')
执行结果如下:
Parent process 928.
Process will start.
Run child process test (929)...
Process end.
创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动。
join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
二、Pool类
如果要启动大量的子进程,可以用进程池的方式批量创建子进程。
multiprocessing模块提供了一个Pool类,可以提供指定数量的进程供用户调用。
当有新的请求提交到Pool中时,如果池还没有满,就会创建一个新的进程来执行请求。如果池满,请求就会告知先等待,直到池中有进程结束,才会创建新的进程来执行这些请求。
2.1 举例:
例1:
from multiprocessing import Pool
import os, time, random def long_time_task(name):
print('Run task %s (%s)...' % (name, os.getpid()))
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Pool(4)
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
执行结果:
Parent process 669.
Waiting for all subprocesses done...
Run task 0 (671)...
Run task 1 (672)...
Run task 2 (673)...
Run task 3 (674)...
Task 2 runs 0.14 seconds.
Run task 4 (673)...
Task 1 runs 0.27 seconds.
Task 3 runs 0.86 seconds.
Task 0 runs 1.41 seconds.
Task 4 runs 1.91 seconds.
All subprocesses done.
例2:
from multiprocessing import Pool
import time def f(x):
return x*x if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
print result.get(timeout=1) # prints "100" unless your computer is *very* slow print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" it = pool.imap(f, range(10))
print it.next() # prints "0"
print it.next() # prints "1"
print it.next(timeout=1) # prints "4" unless your computer is *very* slow result = pool.apply_async(time.sleep, (10,))
print result.get(timeout=1) # raises multiprocessing.TimeoutError
2.2 Pool类下的几个方法简介
1.apply()
函数原型:apply(func[, args=()[, kwds={}]])
该函数用于传递不定参数,同python中的apply函数一致,主进程会被阻塞直到函数执行结束(不建议使用,并且3.x以后不在出现)。
2.apply_async
函数原型:apply_async(func[, args=()[, kwds={}[, callback=None]]])
与apply用法一致,但它是非阻塞的且支持结果返回后进行回调。
Pool.apply_async is also like Python's built-in apply, except that the call returns immediately instead of waiting for the result. An ApplyResult object is returned.
You call its get() method to retrieve the result of the function call. The get() method blocks until the function is completed.
3.map()
函数原型:map(func, iterable[, chunksize=None])
Pool类中的map方法,与内置的map函数用法行为基本一致,它会使进程阻塞直到结果返回。
注意:虽然第二个参数是一个迭代器,但在实际使用中,必须在整个队列都就绪后,程序才会运行子进程。
4.map_async()
函数原型:map_async(func, iterable[, chunksize[, callback]])
与map用法一致,但是它是非阻塞的。其有关事项见apply_async。
5.close()
关闭进程池(pool),使其不在接受新的任务。
6.terminal()
结束工作进程,不在处理未处理的任务。
7.join()
主进程阻塞等待子进程的退出, join方法要在close或terminate之后使用。
2.3 apply_async,apply,map,map_async 的区别
Notice also that you could call a number of different functions with Pool.apply_async (not all calls need to use the same function).
In contrast, Pool.map applies the same function to many arguments. However, unlike Pool.apply_async, the results are returned in an order corresponding to the order of the arguments.
Like Pool.apply, Pool.map blocks until the complete result is returned.
In Python 3, a new function starmap can accept multiple arguments.
Multi-args Concurrence Blocking Ordered-results
map no yes yes yes
apply yes no yes no
map_async no yes no yes
apply_async yes yes no no
三、Queue/Pipe
3.1 queue
class multiprocessing.Queue([maxsize])¶
Returns a process shared queue implemented using a pipe and a few locks/semaphores. When a process first puts an item on the queue a feeder thread is started which transfers objects from a buffer into the pipe.
The usual Queue.Empty and Queue.Full exceptions from the standard library’s Queue module are raised to signal timeouts.
举例:
from multiprocessing import Process, Queue def f(q):
q.put([42, None, 'hello']) if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
3.2 Pipe
multiprocessing.Pipe([duplex])¶
Returns a pair (conn1, conn2) of Connection objects representing the ends of a pipe.
If duplex is True (the default) then the pipe is bidirectional. If duplex is False then the pipe is unidirectional: conn1 can only be used for receiving messages and conn2 can only be used for sending messages
Pipe()函数的作用是:返回由管道连接的一对连接对象,该管道在默认情况下是双向的。例如:
from multiprocessing import Process, Pipe def f(conn):
conn.send([42, None, 'hello'])
conn.close() if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
Pipe()返回的两个连接对象表示管道的两端。每个连接对象都有send()和recv()方法。
请注意,如果两个进程(或线程)试图同时从管道的相同一端读取或写入数据,管道中的数据可能会损坏。当然,在同时使用管道的不同端点的过程中不存在损坏的风险
官网:
https://docs.python.org/2/library/multiprocessing.html
感谢:
https://blog.csdn.net/xluren/article/details/46861621
https://www.cnblogs.com/freeman818/p/7154089.html#undefined
http://blog.shenwei.me/python-multiprocessing-pool-difference-between-map-apply-map_async-apply_async/
multiprocessing的更多相关文章
- Python标准模块--multiprocessing
1 模块简介 multiprocessing模块在Python2.6中引入.最初的multiprocessing是由Jesse Noller和Richard Oudkerk在PEP 371中定义.就像 ...
- Python的多线程(threading)与多进程(multiprocessing )
进程:程序的一次执行(程序载入内存,系统分配资源运行).每个进程有自己的内存空间,数据栈等,进程之间可以进行通讯,但是不能共享信息. 线程:所有的线程运行在同一个进程中,共享相同的运行环境.每个独立的 ...
- python进程池:multiprocessing.pool
本文转至http://www.cnblogs.com/kaituorensheng/p/4465768.html,在其基础上进行了一些小小改动. 在利用Python进行系统管理的时候,特别是同时操作多 ...
- 第十天 多进程、协程(multiprocessing、greenlet、gevent、gevent.monkey、select、selector)
1.多进程实现方式(类似于多线程) import multiprocessing import time,threading def thread_run():#定义一个线程函数 print(&quo ...
- python中的进程、线程(threading、multiprocessing、Queue、subprocess)
Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...
- python中多进程(multiprocessing)
一.multiprocessing中使用子进程概念 from multiprocessing import Process 可以通过Process来构造一个子进程 p = Process(target ...
- an alternative to symmetric multiprocessing
COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION 17.5 CLUSTERSAn impor ...
- 使用 multiprocessing.dummy 执行多线程任务
# -*- coding: utf-8 -*- # from multiprocessing import Pool 多进程 from multiprocessing.dummy import Poo ...
- multiprocessing module in python(转)
序.multiprocessing python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程.Python提供了非常好用的多进程包mu ...
- Python标准库11 多进程探索 (multiprocessing包)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在初步了解Python多进程之后,我们可以继续探索multiprocessing包 ...
随机推荐
- 271. 杨老师的照相排列【线性DP】
杨老师希望给他的班级拍一张合照. 学生们将站成左端对齐的多排,靠后的排站的人数不能少于靠前的排. 例如,12名学生(从后向前)可以排列成每排5,3,3,1人,如下所示: X X X X X X X X ...
- CentOS7安装GUI图形界面
本文转自centOS7下安装GUI图形界面,侵权删. 1. 在命令行下 输入下面的命令来安装Gnome包. # yum groupinstall "GNOME Desktop" & ...
- Java核心知识盘点(一)- 数据存储
MySQL 索引使用的注意事项 1.索引的目的:在于提高查询效率,插入和更新的操作,数据库的操作是慢的,但是查询操作会非常快,索引可以对表中一个或多个字段进行加索引动作. 2.索引的类型: 1.唯一索 ...
- UVA10163 Storage Keepers (动态规划)
$dp[i][j]$表示前$i$个仓库由前$j$个人来守卫能取得的最大安全值: $cost[i][j]$表示前$i$个仓库由前$j$个人来守护在能取得的最大安全值的情况下的最小花费. AC代码 //# ...
- Codeforces 803C. Maximal GCD
题目链接:http://codeforces.com/contest/803/problem/C 中了若干trick之后才过... k个数的严格递增序列最小权值和就是${n*(n+1)/2}$,枚举这 ...
- C++_day06_运算符重载_智能指针
1.只有函数运算符可以带缺省函数,其他运算符函数主要由操作符个数确定 2.解引用运算符和指针运算符 示例代码: #include <iostream> using namespace st ...
- setTimeout异步
同步任务和异步任务 同步和异步操作的区别就是是否阻碍后续代码的执行. 同步任务是那些没有被引擎挂起.在主线程上排队执行的任务.只有前一个任务执行完毕,才能执行后一个任务. 异步任务是那些被引擎放在一边 ...
- Shiro 与spring 整合的及简单使用(转)
文章完全转载自: http://www.cnblogs.com/learnhow/p/5694876.html ,大家可以点击访问原文链接,个人仅作学习收藏 ! 本篇内容大多总结自张开涛的<跟 ...
- 2019.4.24(js)
1. 取得正数和负数的绝对值 Math.abs(7.25) Math.abs(-7.25) 2.利用JS刷新页面方法 https://www.cnblogs.com/Chen-XiaoJun/p/62 ...
- 【架构设计】Android:配置式金字塔架构
最近做一个项目,在项目搭建之前,花了些许时间去思考一下如何搭建一个合适的架构.一开始的构思是希望能合理的把应用的各部分进行分离,使其像金字塔一样从上往下,下层为上层提供功能. 在平常项目中,总是有很多 ...