python 多进程-基础

本文介绍Python实现多进程的两种主要方式:使用os模块的fork方法和multiprocessing模块。前者适用于Unix/Linux系统,后者跨平台。通过示例代码展示如何创建和运行子进程,包括获取进程ID、创建多个子进程并实现进程间同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    Python 实现多进程的方式主要有两种,一种方法是使用 os 模块的 fork 方法,另一种是使用 multiprocessing 模块。

    区别:os.fork 适用于nuix/linux操作系统,不适用于windows系统,multiprocessing 跨平台。

1、使用os.fork方式实现多进程

    python的os模块中的fork方法。来自于nuix/linux操作系统中提供的一个fork系统调用,这个方法非常特殊。普通的方法都是调用一次,返回一次,而fork方法是调用一次,返回两次,原因在于操作系统将当前进程(父进程)复制出一份进程(子进程),这两个进程几乎完全相同,于是fork方法分别在父进程和子进程中返回。子进程中返回永远是0,父进程中返回的是子进程的ID。示例:

    os.getpid() 获取当前进程的ID;

    os.getppid() 获取父进程的ID;

[root@jier ceshi]# cat ceshi.py 
import os
if __name__ == '__main__':
    print('current Process (%s) start ...'%(os.getpid()))
    pid = os.fork()
    if pid < 0:
        print('error in fork')
    elif pid == 0:
        print('I an child process (%s) and my parent process is (%s)'%(os.getpid(), os.getppid()))
    else:
        print('I (%s) created a child process (%s)'%(os.getpid(), pid))
[root@jier ceshi]# 
[root@jier ceshi]# 
[root@jier ceshi]# python ceshi.py 
current Process (18606) start ...
I (18606) created a child process (18639)
I an child process (18639) and my parent process is (18606)
[root@jier ceshi]# 

2、使用 multiprocessing 模块创建多进程

    multiprocessing 模块提供了一个Process 类来描述一个进程对象。创建子进程时,只需要传入一个执行函数和函数对应的参数,即可完成一个Process 实例的创建,用start() 方法启动进程,用join() 方法实现进程间的同步。示例:

[root@jier ceshi]# cat ceshi.py 
import os
from multiprocessing import Process
def run_proc(name):
    print('Child process %s (%s) Running...'%(name, os.getpid()))
if __name__ == '__main__':
    print('Parent process %s.' %os.getpid())
    for i in range(5):
        p = Process(target = run_proc, args = (str(i),))
        print('Process will start.')
        p.start()
    p.join()
print('Process end.')
[root@jier ceshi]# python ceshi.py 
Parent process 19808.
Process will start.
Process will start.
Process will start.
Process will start.
Process will start.
Child process 0 (19841) Running...
Child process 3 (19844) Running...
Child process 2 (19843) Running...
Child process 4 (19845) Running...
Process end.
Child process 1 (19842) Running...
[root@jier ceshi]# 

    注释:函数 run_proc 就是一个进程函数;

    p = Process(target = run_proc, args = (str(i),))  就是创建子进程的时候传入的一个执行函数 run_proc 以及函数的参数 range(5);

    用start()方法启动进程;

    用join()方法实现进程间的同步。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

运维家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值