python中的多进程处理
转载于:http://blog.csdn.net/jj_liuxin/article/details/3564365
帮助文档见https://docs.python.org/2.7/library/multiprocessing.html
众所周知,python本身是单线程的,python中的线程处理是由python解释器分配时间片的;但在python 3.0中吸收了开源模块,开始支持系统原生的进程处理——multiprocessing.
注意:这个模块的某些函数需要操作系统的支持,例如,multiprocessing.synchronize模块在某些平台上引入时会激发一个ImportError
1)Process
要创建一个Process是很简单的。
from multiprocessing import Process
def f(name):
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
要获得一个Process的进程ID也是很简单的。
from multiprocessing import Process
import os
def info(title):
print title
print 'module name:', __name__
print 'parent process:', os.getppid()#这个测试不通过,3.0不支持
print 'process id:', os.getpid()
def f(name):
info('function f')
print 'hello', name
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
创建进程:multiprocessing.Process([group[, target[, name[, args[, kargs]]]]])
参数:
group: None,它的存在仅仅是为了与threading.Thread兼容
target: 一般是函数
name: 进程名
args: 函数的参数
kargs: keywords参数
函数:
run() 默认的run()函数调用target的函数,你也可以在子类中覆盖该函数
start() 启动该进程
join([timeout]) 父进程被停止,直到子进程被执行完毕。
当timeout为None时没有超时,否则有超时。
进程可以被join很多次,但不能join自己
is_alive()
terminate() 结束进程。
在Unix上使用的是SIGTERM
在Windows平台上使用TerminateProcess
属性:
name 进程名
daemon 守护进程
pid 进程ID
exitcode 如果进程还没有结束,该值为None
authkey
2)Queue
Queue类似于queue.Queue,一般用来进程间交互信息
例子:
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()
注意:Queue是进程和线程安全的。
Queue实现了queue.Queue的大部分方法,但task_done()和join()没有实现。
创建Queue:multiprocessing.Queue([maxsize])
函数:
qsize() 返回Queue的大小
empty() 返回一个boolean值表示Queue是否为空
full() 返回一个boolean值表示Queue是否满
put(item[, block[, timeout]])
put_nowait(item)
get([block[, timeout]])
get_nowait()
get_no_wait()
close() 表示该Queue不在加入新的元素
join_thread()
cancel_join_thread()
3)JoinableQueue
创建:multiprocessing.JoinableQueue([maxsize])
task_done()
join()
4)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()
multiprocessing.Pipe([duplex]) 返回一个Connection对象
5)异步化synchronization
from multiprocessing import Process, Lock
def f(l, i):
l.acquire()
print('hello world', i)
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()
6)Shared Memory
from multiprocessing import Process, Value, Array
def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i]
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
p = Process(target=f, args=(num, arr))
p.start()
p.join()
print(num.value)
print(arr[:])
1>Value
2>Array
7)Manager
from multiprocessing import Process, Manager
def f(d, l):
d[1] = ''
d[''] = 2
d[0.25] = None
l.reverse()
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
l = manager.list(range(10))
p = Process(target=f, args=(d, l))
p.start()
p.join()
print(d)
print(l)
8)Pool
from multiprocessing import Pool
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
print result.get(timeout=1) # prints "100" unless your computer is *very* slow
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
multiprocessing.Pool([processes[, initializer[, initargs]]])
函数:
apply(func[, args[, kwds]])
apply_async(func[, args[, kwds[, callback]]])
map(func,iterable[, chunksize])
map_async(func,iterable[, chunksize[, callback]])
imap(func, iterable[, chunksize])
imap_unordered(func, iterable[, chunksize])
close()
terminate()
join()
from multiprocessing import Pool
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
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(next(it)) # prints "0"
print(next(it)) # prints "1"
print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
import time
result = pool.apply_async(time.sleep, (10,))
print(result.get(timeout=1)) # raises TimeoutError
9)杂项
multiprocessing.active_children() 返回所有活动子进程的列表
multiprocessing.cpu_count() 返回CPU数目
multiprocessing.current_process() 返回当前进程对应的Process对象
multiprocessing.freeze_support()
multiprocessing.set_executable()
10)Connection对象
send(obj)
recv()
fileno()
close()
poll([timeout])
send_bytes(buffer[, offset[, size]])
recv_bytes([maxlength])
recv_bytes_info(buffer[, offset])
>>> from multiprocessing import Pipe
>>> a, b = Pipe()
>>> a.send([1, 'hello', None])
>>> b.recv()
[1, 'hello', None]
>>> b.send_bytes('thank you')
>>> a.recv_bytes()
'thank you'
>>> import array
>>> arr1 = array.array('i', range(5))
>>> arr2 = array.array('i', [0] * 10)
>>> a.send_bytes(arr1)
>>> count = b.recv_bytes_into(arr2)
>>> assert count == len(arr1) * arr1.itemsize
>>> arr2
array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
python中的多进程处理的更多相关文章
- Python中使用多进程来实现并行处理的方法小结
进程和线程是计算机软件领域里很重要的概念,进程和线程有区别,也有着密切的联系,先来辨析一下这两个概念: 1.定义 进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和 ...
- 聊聊Python中的多进程和多线程
今天,想谈一下Python中的进程和线程. 最近在学习Django的时候,涉及到了多进程和多线程的知识点,所以想着一下把Python中的这块知识进行总结,所以系统地学习了一遍,将知识梳理如下. 1. ...
- 深入浅析python中的多进程、多线程、协程
深入浅析python中的多进程.多线程.协程 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源 ...
- 学习笔记--python中使用多进程、多线程加速文本预处理
一.任务描述 最近尝试自行构建skip-gram模型训练word2vec词向量表.其中有一步需要统计各词汇的出现频率,截取出现频率最高的10000个词汇进行保留,形成常用词词典.对于这个问题,我建立了 ...
- python中的多进程与多线程(二)
1.使用多线程可以有效利用CPU资源,线程享有相同的地址空间和内存,这些线程如果同时读写变量,导致互相干扰,就会产生并发问题,为了避免并发问题,绝不能让多个线程读取或写入相同的变量,因此python中 ...
- 关于python中的多进程模块multiprocessing
python中的multiprocessing是一个多进程管理包,主要作用也就是提供多进程,而不是多线程,在其中用的比较多估计也就是Process和Pipe两个类,如下代码所示: #!/usr/bin ...
- Python中的多进程、多线程和协程
本文中的内容来自我的笔记.撰写过程中参考了胡俊峰老师<Python程序设计与数据科学导论>课程的内容. 并发处理:多进程和多线程 前置 概念: 并发:一段时间内同时推进多个任务,但不一定要 ...
- Python中的多进程与多线程(一)
一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...
- Python中的多进程与多线程(二)
在上一章中,学习了Python多进程编程的一些基本方法:使用跨平台多进程模块multiprocessing提供的Process.Pool.Queue.Lock.Pipe等类,实现子进程创建.进程池(批 ...
随机推荐
- Luis创建与发布
首先打开网址https://www.luis.ai,打开后,需要使用你的微软帐户或是公司账户登录至Luis 登陆进入至网站后,会自动显示你的应用,在这里你可以修改和删除你之前已经创建过的应用,如果之前 ...
- [转]python dubbo接口测试
转自:https://www.cnblogs.com/chunyanxu/p/8732734.html 会吐泡泡的鱼 博客园 首页 新闻 新随笔 联系 管理 订阅 随笔- 57 文章- 0 评论- ...
- (5)python 字符串和输入输出
一.字符串转义 字符串可以包含任何字符可以用单引号也可以用双引号 a='hello' a="hello" 如果字符串中存在单引号,可以用双引号里包含单引号的方式 a="I ...
- 0103 最短Hamilton路径【状压DP】
0103 最短Hamilton路径 0x00「基本算法」例题 描述 给定一张 n(n≤20) 个点的带权无向图,点从 0~n-1 标号,求起点 0 到终点 n-1 的最短Hamilton路径. Ham ...
- HDU 1280 前m大的数(排序,字符串)
前m大的数 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- Codeforces 691C. Exponential notation
题目链接:http://codeforces.com/problemset/problem/691/C 题意: 给你一个浮点数,让你把这个数转化为 aEb 的形式,含义为 a * 10b, 其中 a ...
- 树状数组【CF703D】Mishka and Interesting sum
Description 给你n( 1<=n<=1000000)个数,以及m(1<=m<=1000000)个询问,每个询问包括l和r,问你在这n个数中,区间l~r,出现偶数个数的 ...
- DataNucleus(通过jpa和jdo接口访问多中数据源)
DataNucleus主页:http://www.datanucleus.org/index.html 简介: DataNucleus项目为Java运行环境中的应用数据提供了管理,它提供了标准的接口( ...
- 【2-SAT】URAL - 2089 - Experienced coach
题意:给出n对点a,b 要求从没对点中选出一个,且最终选出的点n个数不能存在相同的.输入数据满足每种数最多出现3次,最少出现1次 思路:第i对点的编号2*i, 2*i+1, 因为每个数最多出现3 ...
- 计算最大公约数 Exercise05_14
import java.util.Scanner; /** * @author 冰樱梦 * 时间:2018年下半年 * 题目:计算最大公约数 * */ public class Exercise05_ ...