首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中终止进程

在Python中终止进程
EN

Stack Overflow用户
提问于 2020-07-17 01:40:22
回答 1查看 39关注 0票数 0

我对python中的MultiProcessing这个概念还不熟悉。

我有这个代码

代码语言:javascript
复制
import os, time
from multiprocessing import Process, current_process


def square(number):
    """The function squares whatever number it is provided."""
    result = number * number

    # We can use the OS module in Python to print out the process ID
    # assigned to the call of this function assigned by the operating
    # system.
    proc_id = os.getpid()
    print(f"Process ID: {proc_id}")

    # We can also use the "current_process" function to get the name
    # of the Process object:
    process_name = current_process().name
    print(f"Process Name: {process_name}")

    print(f"The number {number} squares to {result}.")


if __name__ == '__main__':

    # The processes list will store each call we make to "square" and the
    # numbers list contains the numbers we loop through and call the
    # "square" function on."
    processes = []
    numbers = [1, 2, 3, 4, 5]

    # Loop through the list of numbers, call the "square" function,
    # and store and start each call to "square".
    for i, number in enumerate(numbers):
        process = Process(target=square, args=(number,))
        processes.append(process)

        # Processes are spawned by creating a Process object and
        # then calling its start() method.
        process.start()

        if number == 2:
            process.terminate()
            time.sleep(0.01)
            print(process.is_alive())


        #print(process.is_alive())

那么会发生什么呢?我只是想检查一个进程是否还在运行。我只是感到困惑,因为我正在调用terminate函数,如果我删除了time.sleep(0.01),它将返回True,这意味着进程仍然活着!

但是当我放入time.sleep(0.01)时,它会打印出False!这意味着进程被终止了,对吗?那么,为什么这个time.sleep(0.01)是一件大事呢?我是不是漏掉了什么?关于这个我肯定有些不明白的地方。但是请随时告诉我,如果你愿意演示一个示例代码,让我更好地理解,请成为我的客人,我会很高兴的!

包含time.sleep(0.01)时的输出

代码语言:javascript
复制
False
Process ID: 1808
Process Name: Process-1
The number 1 squares to 1.
Process ID: 17180
Process Name: Process-3
The number 3 squares to 9.
Process ID: 2488
Process Name: Process-5
The number 5 squares to 25.
Process ID: 16656
Process Name: Process-4
The number 4 squares to 16.
[Finished in 1.0s]

如果被移除,那么

代码语言:javascript
复制
True
Process ID: 1808
Process Name: Process-1
The number 1 squares to 1.
Process ID: 17180
Process Name: Process-3
The number 3 squares to 9.
Process ID: 2488
Process Name: Process-5
The number 5 squares to 25.
Process ID: 16656
Process Name: Process-4
The number 4 squares to 16.
[Finished in 1.0s]

我真的被MultiProcessing迷住了。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-07-17 01:58:54

进程本质上是在告诉python使用自己的内存和所有东西来运行一个新的python实例。这意味着每个进程都有一个启动和关闭步骤,这不是微不足道的。当您立即终止并检查时,没有足够的时间让进程实际自行终止。所需的确切时间将取决于您的平台。这是多处理的一个重要部分,多处理并不总是能节省时间。每个子进程的开销仍然需要由主线程来处理。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62940502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档