简体   繁体   English

Python进程阻塞主线程

[英]Python process blocking main thread

I can't figure out why a Python process would block the main thread.我不明白为什么 Python 进程会阻塞主线程。 An example:一个例子:

import multiprocessing
import time


def do_something(name: str):
    while True:
        print(name)


if __name__ == '__main__':
    p1 = multiprocessing.Process(target=do_something, args=(1,))
    p1.start()

    p2 = multiprocessing.Process(target=do_something, args=(2,))
    p2.start()

    while True:
        print(3)
        time.sleep(.1)

The output result of this is a whole bunch of 1 and 2's.其输出结果是一大堆 1 和 2。 While 3 (main process/thread) is never printed.虽然 3(主进程/线程)从不打印。 When I remove the time.sleep it starts printing again.当我删除 time.sleep 时,它会再次开始打印。 Why is it that a time.sleep can make Processes block the main thread?为什么 time.sleep 可以让进程阻塞主线程?

如果将输出通过管道传输到文本文件,您会发现它确实打印了 3。但是,它大约每 100 毫秒打印一次,而其他两个进程连续打印,因此您可能在控制台中看不到它。

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

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