我正在学习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()
答案 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的属性,而不是函数。