在Python中杀死进程



我对python 中的多处理概念很陌生

我有这个代码

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)时的输出

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]

如果移除,则

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。非常感谢。

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

相关内容

  • 没有找到相关文章

最新更新