Jupyter Notebook与命令行中Python threading线程数不一致问题
为什么Jupyter Notebook和命令行运行threading代码的输出不一致?
核心原因是Jupyter Notebook的输出捕获机制与线程执行的时机差导致的,具体拆解如下:
命令行环境的输出逻辑
当你调用hello_thread.start()启动子线程后,主线程会立即继续执行后续代码。虽然子线程里只是执行一句打印,但命令行的IO操作更直接,主线程执行到active_count()时,子线程还处于运行状态(尚未完成退出),因此active_count()会统计到主线程+正在运行的子线程两个线程,输出结果为2 thread(s)。
Jupyter Notebook环境的输出逻辑
Jupyter为了把线程中的输出转发到前端界面,会对线程的IO操作做特殊处理,这个转发过程存在微小延迟。而主线程的执行速度极快,在子线程完成所有操作(包括输出转发)并退出前,主线程已经执行到了active_count(),此时子线程已经结束,所以active_count()仅统计到当前的主线程,输出结果为1 thread(s)。
验证方法
如果给子线程加一段短暂休眠,延长其存活时间,就能让Jupyter的输出和命令行保持一致:
import threading import time def hello_from_thread(): print(f'Hello from thread {threading.current_thread()}!') time.sleep(0.1) # 让子线程多存活一段时间 hello_thread = threading.Thread(target=hello_from_thread) hello_thread.start() total_threads = threading.active_count() thread_name = threading.current_thread().name print(f'Python is currently running {total_threads} thread(s)') print(f'The current thread is {thread_name}') hello_thread.join()
此时Jupyter中active_count()也会显示2 thread(s),因为主线程统计时子线程仍处于休眠状态,尚未退出。
内容的提问来源于stack exchange,提问作者mayankkaizen
相关产品推荐
相关产品推荐

