为什么我的子进程要创建一个新进程,它从父进程继承了什么?

Why is my child process creating a new process, and what does it inherit from its parent process?

from multiprocessing import Process, cpu_count
import time
def count(element):
    count_value = 0
    while count_value < element:
        count_value += 1

x = Process(target=count, args=(1000000000,))
x.start()
print(cpu_count())
x.join()

print(cpu_count())
print(time.perf_counter())

当我执行上面的代码时,出现运行时错误:

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

现在我的问题是,我的子进程从其父进程继承了什么才会发生这种错误?

这是因为您的程序的主要部分应该在 if __name__ == '__main__': 块下。这是因为您希望新进程使用的函数在主文件中,因此新解释器会尝试导入主文件。这导致它 运行 所有代码,包括尝试启动一个新进程,这就是导致错误的原因。所有这些行为都记录在案 here.