总的来说与多线程的实现方式几乎一致. 不同的点在于多进程间的变量通信
from multiprocessing import Process
import time
import os
class MyProcess(Process):
def __init__(self):
super().__init__()
def run(self): # 实现自己的Process类时, 需要重写Process方法
print(f"启动子进程. pid: {os.getpid()}")
time.sleep(10)
print(f"结束子进程. pid: {os.getpid()}")
def f():
print(f"启动子进程. pid: {os.getpid()}")
time.sleep(10)
print(f"结束子进程. pid: {os.getpid()}")
if __name__ == "__main__":
ps = []
# 实现多进程的第一种方式, 继承Process类, 重写run方法. -- MyProcess
for i in range(1, 11):
ps.append(MyProcess())
# 实现多进程的第二种方式, target指定f函数
for i in range(1, 11):
ps.append(Process(target=f))
for p in ps:
p.start() # 启动子进程
for p in ps:
p.join() # 阻塞主进程直到子进程结束为止
print("end")
在多个进程间共享数据
from multiprocessing import Process, Queue
import time
import os
def f(q):
print(f"启动子进程. pid: {os.getpid()}")
time.sleep(1)
q.put(q.get() + 1)
print(f"结束子进程. pid: {os.getpid()}")
if __name__ == "__main__":
ps = []
q = Queue() # 实例化队列 Queue
q.put(0) # 将 0 放入初始数据
for i in range(1, 11):
ps.append(Process(target=f, args=(q,)))
for p in ps:
p.start() # 启动子进程
for p in ps:
p.join() # 阻塞主进程直到子进程结束为止
print(q.get())
print("end")
原文:https://www.cnblogs.com/gopher-zero/p/15240854.html