为什么这两个进程会这样?

Why do these two processes behave like this?

我在这里创建了一个进程的两个实例,但是当我运行这个程序时,我只得到主函数输出。

import multiprocessing
import time

def sleepy_man():
    print("Starting to Sleep")
    time.sleep(1)
    print("Done Sleeping")

tic = time.time()
p1 = multiprocessing.Process(target=sleepy_man)
p2 = multiprocessing.Process(target=sleepy_man)
p1.start()
p2.start()

toc = time.time()

print("Done in {:.4f} seconds".format(toc-tic))

输出

Done in 0.0554 seconds

我这样做只是为了练习这个博客。 资料来源:https://www.analyticsvidhya.com/blog/2021/04/a-beginners-guide-to-multi-processing-in-python/

值得注意的是,如果您以某种方式设置 p1.daemon = p2.daemon = True.

,您会看到相同的行为

这也可能是由于输出缓冲,而不是逻辑错误。 两个问题:

  • 如果您将 sys.stdout.flush()flush=True 添加到 print,您会看到不同的行为吗?
  • 如果你用 time python foobar.py 运行 这个 运行 需要 .02 秒还是 1 秒?

显然,继续您的教程并在下面正确添加 .join() 将以正常使用预期的方式解决问题。

import multiprocessing as mp
import time


def sleepy_man():
    print("Starting to Sleep")
    time.sleep(1)
    print("Done Sleeping")


# if you are on Windows, which use spawning to create child processes, use __name__ == '__main__'
if __name__ == '__main__':
    tic = time.time()
    processes = [
        mp.Process(target=sleepy_man),
        mp.Process(target=sleepy_man)
    ]
    [p.start() for p in processes]
    # if you want to see results of process work, join them
    # otherwise if main process finish its work before their children
    # you'll get no results since parent process will finish children 
    # you can also declare Process as daemon=False - as another choice
    # in that case you can use no join()
    # on the other hand join() makes parent process to wait for children join()
    # and only then it prints time in your case
    [p.join() for p in processes]
    toc = time.time()
    print("Done in {:.4f} seconds".format(toc-tic))