繁体   English   中英

Jupyter Notebook 多处理代码不起作用

[英]Jupyter Notebook Multiprocessing code not working

我是 python 的新手,我有 Anaconda Pyton 3.9 我正在研究多处理。

当我尝试这段代码时

from multiprocessing import Process # gerekli kütüphaneyi çağıracağız.

import time

def subfunc1():
    time.sleep(2)
    print("subfunc1: Baslatildi")
    time.sleep(2)
    print("subfunc1: Sonlandi")
    time.sleep(2)

def subfunc2():
    time.sleep(2)
    print("subfunc2: Baslatildi")
    time.sleep(2)
    print("subfunc2: Sonlandi")
    time.sleep(2)
    
def mainfunc():
    print("mainfunc: Baslatildi")
    pr1 = Process(target=subfunc1)
    pr2 = Process(target=subfunc2)
    pr1.start()
    pr2.start()
    print("mainfunc: Sonlandi")
    
if __name__ == '__main__': # Main kod bloğunun içerisindeyken main fonk çağır!
    mainfunc()

result is

    mainfunc: Baslatildi
    mainfunc: Sonlandi

当我将 Visual Code 与 Python 3.9 一起使用时,我有一个虚拟和代码工作。 Visual Code 在虚拟环境中使用 Anaconda 的 python 3.9!

请你帮助我好吗? 为什么这段代码不能在 Jupyter Notebook 中正常工作?

谢谢

假设您在 ms-windows 或 macOS 上运行它,我是否正确?

在这种情况下, multiprocessing将无法在 IPython 等交互式解释器中工作。 这在文档中有所介绍,请参阅“注释”:

此 package 中的功能要求__main__模块可由子模块导入。 这在编程指南中有介绍,但值得在这里指出。 这意味着某些示例,例如multiprocessing.pool.Pool示例将无法在交互式解释器中工作。

这是由这些操作系统上使用的spawn start 方法引起的。

解决方法是将代码保存在脚本中,并确保在__main__ -block 中创建multiprocessing对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM