multiprocessing模块的多进程与进程池
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了multiprocessing模块的多进程与进程池相关的知识,希望对你有一定的参考价值。
multiprocessing模块的Process方法
可以利用Proces方法在一个主进程中创建几个子进程
from multiprocessing import Process
import time
def f1(name):
time.sleep(2)
print(‘Hell %s‘ % name)
def f2(age):
time.sleep(2)
print(‘Hell %s‘ % age)
if __name__ == "__main__":
p = Process(target=f1,args=(‘ayu‘,))
p.daemon = True #将daemon设置为True,则主进程不等待子进程,主进程结束,则整个进程结束
p.start()
p = Process(target=f2,args=(‘22‘,))
p.daemon = True
p.start()
print(‘All Done‘) #子进程结束后会输出
###进程间的内存是不共享的
from multiprocessing import Process
li = []
def ad(i):
li.append(i)
print(li)
if __name__ == "__main__":
for i in range(10):
p = Process(target=ad,args=(i))
p.start()
/Users/wuxiangyu-pc/.conda/envs/test_all/bin/python /Users/wuxiangyu-pc/Documents/spider/test_all/fork_process.py
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
说明各个进程间,内存是不能共享的
但是线程之间内存是可以共享的,所以可以使用threading操作
from threading import Thread
li = []
def ad(i):
li.append(i)
print(li)
if __name__ == "__main__":
for i in range(10):
p = Thread(target=ad,args=(i,))
p.start()
/Users/wuxiangyu-pc/.conda/envs/test_all/bin/python /Users/wuxiangyu-pc/Documents/spider/test_all/fork_process.py
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0
要实现进程间的内存共享,可以使用Manager方法
from multiprocessing import Process,Manager
def ad(i,li):
li.append(i)
print(li)
if __name__ == "__main__":
manager = Manager()
li = manager.li()
for i in range(10):
p = Process(target=ad,args=(i,li))
p.start()
p.join()
/Users/wuxiangyu-pc/.conda/envs/test_all/bin/python /Users/wuxiangyu-pc/Documents/spider/test_all/fork_process.py
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0
##multiprocessing模块的Pool进程池
Pool.apply方法可以实现多个子进程排序依次执行
from multiprocessing import Pool
import time
def f0(name):
time.sleep(2)
print(‘i am %s‘ % name)
if __name__ == "__main__":
p = Pool(5)
for i in range(5):
p.apply(func=f0,args=(i,))
print(‘Hello World‘)
p.close()
p.join()
Pool.apply_async实现多线程异步,比apply多一个回调函数
from multiprocessing import Pool
def f1(num):
i = num + 20
return i
def f1(i):
print(‘i am %s‘ % i)
if __name__ == "__main__":
p = Pool(5)
for i in range(5):
p.apply_async(func=f1,args=(i,),callback=f1)
p.close()
p.join()
以上是关于multiprocessing模块的多进程与进程池的主要内容,如果未能解决你的问题,请参考以下文章