码迷,mamicode.com
首页 > 编程语言 > 详细

python ---多进程 Multiprocessing

时间:2019-01-10 23:00:50      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:.com   reading   when   创建   nump   +=   表示   bsp   time   

 

和 threading 的比较 

多进程 Multiprocessing 和多线程 threading 类似, 他们都是在 python 中用来并行运算的. 不过既然有了 threading,

为什么 Python 还要出一个 multiprocessing 呢? 原因很简单, 就是用来弥补 threading 的一些劣势, 比如在 threading 教程中提到的GIL.

 

创建多进程

import multiprocessing as mp
import threading as td

def job(a,b):
    print(a,b)

t1 = td.Thread(target=job,args=(1,2))
p1 = mp.Process(target=job,args=(1,2))

p1.start()

 

结果保存在mp.queue里

 

queue模块实现了面向多生产线程、多消费线程的队列,

multiprocessing.queue模块实现了面向多成产进程、多消费进程的队列

Queue.Queue是进程内非阻塞队列。多进程各自私有

multiprocess.Queue是跨进程通信队列。各子进程共有。

 1 import multiprocessing as mp
 2 import threading as td
 3 
 4 def job(q):
 5     res = 0
 6     for i in range(1000):
 7         res+=i+i**2+i**3        
 8     q.put(res)
 9 
10 
11 q = mp.Queue()
12 p1 = mp.Process(target=job,args=(q,))
13 p2 = mp.Process(target=job,args=(q,))
14 p1.start()
15 p2.start()
16 p1.join()
17 p2.join()
18 res1 = q.get()
19 res2 = q.get()
20 print(res1+res2)

 

进程池pool

 

https://stackoverflow.com/questions/8533318/multiprocessing-pool-when-to-use-apply-apply-async-or-map

 1 import multiprocessing as mp
 2 
 3 def job(x):
 4     return x*x
 5 pool = mp.Pool()
 6 
 7 pool = mp.Pool() 
 8 res = pool.map(job, range(10))
 9 print(res)
10 
11 
12 
13 res = pool.apply_async(job, (2,))
14 # 用get获得结果
15 print(res.get())

 

定义共享内存

 

其中di参数用来设置数据类型的,d表示一个双精浮点类型,i表示一个带符号的整型。

import multiprocessing as mp

value1 = mp.Value(i, 0) 
value2 = mp.Value(d, 3.14)

 

这里的Array和numpy中的不同,它只能是一维的,不能是多维的。同样和Value 一样,需要定义数据形式,否则会报错。

array = mp.Array(i, [1, 2, 3, 4])

 

 https://docs.python.org/3/library/array.html

加锁

 

 1 import multiprocessing as mp
 2 
 3 def job(v,num,lock):
 4     lock.acquire() # 锁住
 5     for _ in range(10):
 6         time.sleep(0.1)
 7         v.value +=1
 8         print(v.value)
 9     lock.release()
10     
11 
12 l = mp.Lock() # 定义一个进程锁
13 v = mp.Value(i, 0) # 定义共享内存
14 p1 = mp.Process(target=job, args=(v,1,l)) # 需要将lock传入
15 p2 = mp.Process(target=job, args=(v,3,l)) 
16 p1.start()
17 p2.start()
18 p1.join()
19 p2.join()

 

python ---多进程 Multiprocessing

标签:.com   reading   when   创建   nump   +=   表示   bsp   time   

原文地址:https://www.cnblogs.com/zle1992/p/10252730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!