简单的多进程实例(这个需要在linux下通过shell执行)
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Pool
import time
def f(x):
time.sleep(1)
return x*x
if __name__ =="__main__":
p = Pool(3)
#最多放5个进程,以多进程的形式完成map函数的执行调用,直接起了3个进程执行3次调用f函数,也就是并行执行
print (p.map(f,[1,2,3,4,5,6]))
#执行结果:
通过修改Pool(num),你明显可以感觉到一个进程和多个进程执行上面程序的速度。
- 另一种写法
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Process
import os
def info(title):
print title
print 'module name:',__name__
if hasattr(os, 'getppid'):
print 'parent proces:',os.getppid()
#这个PPID是运行ppython程序的tty fork()出来的
print 'process id:',os.getppid()
#tty fork()出来程序的主进程
def f(name):
info('function f')
tty fork()出来的子进程,也就是程序的主进程
print 'hello',name
if __name__ == '__main__':
info('main line')
#
print '------------'
p =Process(target=f,args=('bob',))
#tty fork()出来程序的主进程在fork()一个新的子进程
p.start()
p.join()
#join就是等待进程执行完毕
- 还有一种写法
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Pool
import time
def f(x):
print x*x
time.sleep(1)
return x*x
pool = Pool(processes=4)
res_list = []
for i in range(10):
res = pool.apply_async(f,[i,])
#apply_async这个是异步,apply()是同步,等待这个这个进程执行完毕,在启动下一个进程,相当于串行。
#res.get()
#等到线程执行完毕后,获取线程的执行结果,这是程序在这里阻塞,使程序看起来像单进程。
print '-------',i
res_list.append(res)
for i in res_list:
print i.get()
这里注意一下,除了根进程,其他的进程都是通过其他进程fork()出来,也就是说除了根进城,每个进程都有一个父进程。(这里说的是UNXX,windows好像还不一样)
进程间的内存共享
- 说明进程之间不共享(也可以说明线程之间共享资源,只不过腰间Process换成threading.Thread)
#!/usr/bin/env python
#coding:utf-8
#相当于第三方中转
from multiprocessing import Process
def run(InfoList,n):
InfoList.append(n)
print InfoList
info = []
for i in range(10):
p =Process(target=run,args=[info,i])
p.start()
#执行结果:
我们可以清除的看到,每一个进程都会读进去一个空列表
- 使用Queue实现进程之间的内存共享
也就是多个进程共享一个队列
#这里的Queue可不是普通模块Queue
#!/usr/bin/env python
#coding:utf-8
#相当于第三方中转
from multiprocessing import Process
from multiprocessing import Queue
def f(q,n):
q.put([n,'hello'])
if __name__ == "__main__":
q = Queue()
for i in range(5):
p = Process(target=f,args=(q,i))
p.start()
while True:
print q.get()
#这里如果是普通模块的Queue则会阻塞,因为你进程中的q.put([n,'hello'])和 print q.get()是不同内存中的数据。
#结果:
[0, 'hello']
[1, 'hello']
[2, 'hello']
[3, 'hello']
[4, 'hello']
- 通过Value和Array实现线程内存共享
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Process,Value,Array
def f(n,a):
n.value = 3.14
for i in range(5):
a[i] = -a[i]
if __name__ == '__main__':
num = Value('d',0.0)
arr = Array('i', range(10))
print num.value
print arr[:]
p = Process(target=f,args =(num,arr))
p.start()
p.join()
print num.value
print arr[:]
#结果:
0.0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.14
[0, -1, -2, -3, -4, 5, 6, 7, 8, 9]
- 通过Manager实现内存共享
#!/usr/bin/env python
#coding:utf-8
from multiprocessing import Process,Manager
def f(d,l):
d[1] = '1'
d[2] = '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
#结果:
{0.25: None, 1: '1', 2: '2'}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]