进程是程序执行时的一个实例,每个进程都有独立的内存空间和系统资源。而多进程是指在同一时间内,存在多个进程在系统中运行,这些进程可以并发执行,互不干扰。
使用多进程可以显著提高程序的运行效率。Python中通过使用multiprocessing模块来实现多进程。
创建多进程有两种方式:fork和spawn。在Windows操作系统上使用multiprocessing需要使用spawn方式。
在Unix/Linux系统上可以使用fork方式创建多进程。fork方式是通过在父进程中调用os.fork()方法来创建一个子进程,并且子进程会完全复制父进程的环境变量、资源等。
示例代码:
import os
def child_process():
print(f"Child process id: {os.getpid()}")
def parent_process():
print(f"Parent process id: {os.getpid()}")
print("Create child process.")
pid = os.fork()
if pid == 0:
child_process()
else:
print(f"Created child process with pid: {pid}")
if __name__ == '__main__':
parent_process()
输出:
Parent process id: 12345
Create child process.
Created child process with pid: 23456
Child process id: 23456
在Windows操作系统上使用spawn方式创建多进程。spawn方式是父进程生成一个新的Python解释器实例,并在这个新实例中执行子进程的代码。
示例代码:
from multiprocessing import Process
import os
def child_process():
print(f"Child process id: {os.getpid()}")
def parent_process():
print(f"Parent process id: {os.getpid()}")
print("Create child process.")
p = Process(target=child_process)
p.start()
p.join()
if __name__ == '__main__':
parent_process()
输出:
Parent process id: 12345
Create child process.
Child process id: 23456
多进程之间不能直接共享数据,需要通过进程间通讯来实现数据共享。
multiprocessing模块提供了多种进程间通讯的方式,如:Queue、Pipe等。
Queue是用于进程间通讯的队列,它本身是进程安全的。
示例代码:
from multiprocessing import Process, Queue
import os
import time
def child_process(queue):
print(f"Child process id: {os.getpid()}")
while True:
if not queue.empty():
msg = queue.get()
print(f"Child process received msg: {msg}")
if msg == 'finish':
break
time.sleep(1)
def parent_process():
print(f"Parent process id: {os.getpid()}")
q = Queue()
p = Process(target=child_process, args=(q,))
p.start()
for i in range(5):
q.put(f"msg {i}")
q.put("finish")
p.join()
if __name__ == '__main__':
parent_process()
输出:
Parent process id: 12345
Child process id: 23456
Child process received msg: msg 0
Child process received msg: msg 1
Child process received msg: msg 2
Child process received msg: msg 3
Child process received msg: msg 4
Pipe是用于进程间通讯的管道,它本身也是进程安全的。
示例代码:
from multiprocessing import Process, Pipe
import os
import time
def child_process(conn):
print(f"Child process id: {os.getpid()}")
while True:
msg = conn.recv()
print(f"Child process received msg: {msg}")
if msg == 'finish':
break
conn.close()
def parent_process():
print(f"Parent process id: {os.getpid()}")
conn_parent, conn_child = Pipe()
p = Process(target=child_process, args=(conn_child,))
p.start()
for i in range(5):
conn_parent.send(f"msg {i}")
conn_parent.send("finish")
p.join()
if __name__ == '__main__':
parent_process()
输出:
Parent process id: 12345
Child process id: 23456
Child process received msg: msg 0
Child process received msg: msg 1
Child process received msg: msg 2
Child process received msg: msg 3
Child process received msg: msg 4
本文介绍了Python中使用multiprocessing模块实现多进程和进程间通讯的基础知识。其中包括多进程的创建方式,以及多种进程间通讯的方式。在实际开发中,多进程可以有效提升程序的运行效率,同时进程间通讯也是保证多进程并发执行的关键。