多重处理无法运行

时间:2019-11-08 08:25:28

标签: python multithreading process jupyter-notebook jupyter

我正在学习python多处理,在jupyter笔记本中使用以下代码。但是它无法执行子流程任务功能download_task,只能输出类似0.11.的内容,而不会出错。

当我将此代码复制到在线python执行程序时,它工作正常。

from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep

def download_task():
    time_to_download = randint(5, 10)
    print("befor sleep")
    sleep(time_to_download)
    print("after sleep")
def main():
    start = time()
    p1 = Process(target=download_task)
    p1.start()
    p2 = Process(target=download_task)
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print('%.2f.' % (end - start))

main()

这是jupyter笔记本执行结果的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:1)

我设法通过在函数名称后添加()来解决该问题。

from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep

def download_task():
    time_to_download = randint(5, 10)
    print("befor sleep")
    sleep(time_to_download)
    print("after sleep")
def main():
    start = time()
    p1 = Process(target=download_task())
    p1.start()
    p2 = Process(target=download_task())
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print('%.2f.' % (end - start))

main()

如果在终端上运行,则会看到错误消息:

AttributeError: Can't get attribute 'download_task' on <module '__main__' (built-in)>

显然,通过仅使用download_task,它将download_task视为main的属性,而不是函数。