我对python中的MultiProcessing这个概念还不熟悉。
我有这个代码
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迷住了。谢谢!
发布于 2020-07-17 01:58:54
进程本质上是在告诉python使用自己的内存和所有东西来运行一个新的python实例。这意味着每个进程都有一个启动和关闭步骤,这不是微不足道的。当您立即终止并检查时,没有足够的时间让进程实际自行终止。所需的确切时间将取决于您的平台。这是多处理的一个重要部分,多处理并不总是能节省时间。每个子进程的开销仍然需要由主线程来处理。
https://stackoverflow.com/questions/62940502
复制相似问题