首页 > 解决方案 > time.sleep 似乎阻塞了其他线程

问题描述

我有一个简单的 Python 3 程序,其中一个子线程处于休眠状态,而主线程似乎也被阻塞了。为什么不sleep将cpu切换到主线程?

import threading
import time


def hello():
    print('hello')
    while True:
        time.sleep(10000)


threading.Thread(hello()).start()

print('world')

输出:

hello

这个词world从未印刷过。

标签: python-3.xmultithreading

解决方案


您正在hello通过使用 this 调用主线程,hello()这是一个函数调用(因为()),而不是函数引用。参考(名称)只是hello.

也许尝试:

threading.Thread(target=hello).start()

推荐阅读