我正在尝试运行一个简单的多处理任务,如下所示:
def main():
def do_something():
print('sleeping 1 second')
time.sleep(1)
print('Done sleeping')
p1 = multiprocessing.Process(target=do_something())
p2 = multiprocessing.Process(target=do_something())
p1.start()
p2.start()
if __name__ == '__main__':
main()
输出如下:
sleeping 1 second
Done sleeping
sleeping 1 second
Done sleeping
Process finished with exit code 0
但是我期望输出:
sleeping 1 second
sleeping 1 second
Done sleeping
Done sleeping
Process finished with exit code 0
我使用的是使用vscode的windows机器。似乎多处理并没有完全发挥其功能,我是否必须启用多处理支持或其他东西?
请帮助。谢谢!
进程不是线程,它正在执行不同的任务,进程阻塞直到完成。注意,它也是从线程池延迟的。另外,等待所有的线程都完成.join()
并确保它们正确退出也是一种好做法
import threading as th
import time
def do_something():
print('sleeping 1 second')
time.sleep(1)
print('Done sleeping')
def main():
th_1 = th.Thread(target=do_something)
th_2 = th.Thread(target=do_something)
th_1.start()
th_2.start()
th_1.join()
th_2.join()
if __name__ == '__main__':
main()