Skip to main content
 首页 » 编程设计

Python 多处理不在 Fedora 中创建新进程

2024年10月25日1052php

我正在学习 Python 2.7 中的多处理。我在 Windows 7 和 Fedora 20 中都尝试了以下代码。

代码示例

import multiprocessing 
import time 
 
def worker(): 
    name = multiprocessing.current_process().name 
    print name, 'Starting' 
    time.sleep(10) 
    print name, 'Exiting' 
     
if __name__ == '__main__': 
    worker_1=multiprocessing.Process(target=worker) 
    worker_2=multiprocessing.Process(target=worker) 
     
    worker_1.start() 
    worker_2.start() 

在 Windows-7 中,在任务管理器中我可以看到 3 个 python 进程正在运行。

在 Fedora-20 中 使用命令 top | grep python,我可以看到只有一个 python 进程在运行。

是不是在Linux中,操作系统不允许多处理?

如果多处理程序将像普通程序一样运行,那么为什么人们应该更喜欢 multiprocessing 而不是 Threading?

请您参考如下方法:

问题不在于 Python,而在于使用 top 命令。默认情况下,top 仅显示适合单个屏幕的进程。当您的工作进程处于 sleep 状态时,它们占用的资源很少并且落后。因此,它们不会作为 grep 的结果出现。

您可以使用 ps aux 命令来验证 worker 是否已创建,或者您可以为 top 使用 -b 选项,用于重定向 top 的输出。

顶部-b | grep python

来自 man top :

-b : Batch mode operation Starts top in 'Batch mode', which could be useful for sending out- put from top to other programs or to a file. In this mode, top will not accept input and runs until the iterations limit you've set with the '-n' command-line option or until killed.