Python(多进程multiprocessing模块)

时间:2023-01-18 15:16:31

day31

http://www.cnblogs.com/yuanchenqi/articles/5745958.html

由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessing,只需要定义一个函数,Python会完成其他所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。

多进程

 from multiprocessing import Process#进程
import time
def f(name):
time.sleep(1)
print('hello', name,time.ctime()) if __name__ == '__main__':
p_list=[]
for i in range(3):#和threading,差不多
p = Process(target=f, args=('alvin',))
p_list.append(p)
p.start()
for i in p_list:
p.join()
print('end') #延迟一秒后全部输出

延迟1面。输出。

执行结果:

/home/nizhipeng/PycharmProjects/learnPython/venv/bin/python /home/nizhipeng/PycharmProjects/learnPython/week8/多进程.py
hello alvin Mon Nov 5 22:25:45 2018
hello alvin Mon Nov 5 22:25:45 2018
hello alvin Mon Nov 5 22:25:45 2018
end Process finished with exit code 0

类式调用多线程

 from multiprocessing import Process
import time class MyProcess(Process):#继承
def __init__(self):
super(MyProcess, self).__init__()
#self.name = name 可以从新赋值 def run(self):
time.sleep(1)
print ('hello', self.name,time.ctime())#hello MyProcess-3 Mon Nov 5 21:20:11 2018 if __name__ == '__main__':
p_list=[]
for i in range(3):
p = MyProcess()
p.start()
p_list.append(p) for p in p_list:
p.join() print('end')

使用方式和threading多线程一样。

执行结果:

hello MyProcess-1 Mon Nov  5 22:27:51 2018
hello MyProcess-2 Mon Nov 5 22:27:51 2018
hello MyProcess-3 Mon Nov 5 22:27:51 2018
end Process finished with exit code 0

进程关系

 from multiprocessing import Process
import os
import time
def info(title):
print(title)#传入信息
print('module name:', __name__)#main
print('parent process:', os.getppid())#父进程号
print('process id:', os.getpid())#本进程号
#每一个进程都有根进程 def f(name):
info('\033[31;1mfunction f\033[0m')
print('hello', name) if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
time.sleep(3)
p = Process(target=info, args=('bob',))#子进程 ,其父进程是主进程
p.start()
p.join()

执行结果:

main process line
module name: __main__
parent process: 4319
process id: 1896
bob
module name: __main__
parent process: 1896
process id: 1929 Process finished with exit code 0

从输出结果可以看出,子进程p的父进程号1896是主进程号1896。主进程的父进程号是4319。

每一个进程都有根进程

主进程与子进程通信Pipe

 from multiprocessing import Process, Pipe

 def f(conn):
conn.send([42, None, 'hello'])#其中conn,为其父进程的child_conn
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()

执行结果:

[42, None, 'hello']

Process finished with exit code 0

manager实现数据共享

 from multiprocessing import Process, Manager
import threading
def f(d, l,n):
d[n] = ''#n 为0~1个线程,全赋为1
d[''] = 2
d[0.25] = None
l.append(n)
#print('l:', l) if __name__ == '__main__':
with Manager() as manager: #manager = manager()
d = manager.dict()#字典 l = manager.list(range(5))#初始值为零到四的列表 p_list = []
for i in range(10):
p = Process(target=f, args=(d, l, i))
#p = threading.Thread(target=f, args=(d, l, i)) #多线程
p.start()
p_list.append(p) for res in p_list:
res.join() print(d)
print(l)

执行结果:

{0.25: None, 1: '', 2: '', 3: '', '': 2, 5: '', 6: '', 7: '', 8: '', 9: '', 4: '', 0: ''}
[0, 1, 2, 3, 4, 1, 0, 6, 2, 3, 7, 4, 8, 9, 5] Process finished with exit code 0

d字典中,n 0~9,都赋值为1,其余按要求赋值。

列表l中,前五个初始为0~4,后十个值由于是多进程,排列顺序随机。