Python:多进程函数中的线程与多进程函数或父进程在同一个内核中运行?

Python: Threading within MultiProcess Function runs in the same core as the multiprocess one or the parent one?

def multiprocess_function():
   run = 0   
   while run == 0:
     for i in the range(100):

        #This will initiate 100 threads
        threading.Thread(target=sum, args=(i,0))

     time.sleep(10)

p1 = multiprocessing.Process(target=multiprocess_function)
p1.start

在上面的代码片段中,我开始了一个新的无限循环过程(在一个单独的核心上(比如#2))。在这个函数中,我启动了 100 个线程。线程 运行 会在同一个核心 #2 上还是会 运行 在主 python 核心上?

此外,您可以在一个核心上 运行 多少个线程?

所有线程 运行 在它们启动的进程中。在这种情况下,进程 p1.

关于一个进程中可以 运行 多少个线程,您必须记住,在 CPython 中,一次只能 一个线程执行 Python 字节码 。这是由全局解释器锁(“GIL”)强制执行的。所以对于需要大量计算的作业,通常最好使用进程而不是线程。

如果您查看 concurrent.futures.ThreadPoolExecutor 的文档,默认情况下它使用的工作线程数是物理处理器数量的五倍。对于 ThreadPoolExecutor 适用的各种工作负载来说,这似乎是一个合理的数量。