Python 不会创建线程?

5 投票
2 回答
4138 浏览
提问于 2025-04-17 12:12

我可能漏掉了什么简单的东西,但我在pythonwin里运行我的代码是没问题的,但在命令行里运行时就出错了。

import time, thread
def print_t(name, delay):
    while 1:
        time.sleep(delay)
        print name
try:
    thread.start_new_thread(print_t,("First Message",1,))
    thread.start_new_thread(print_t,("Second Message",2,))
except Exception as e:
    print e

Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr

Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr

2 个回答

2

这是因为主线程结束了,而你使用的是 thread 而不是 threading,所以“子线程”也会一起结束。

最好使用 threading 这个模块。

6

这个错误发生在主线程(也就是启动其他线程的那个线程)结束的时候。在你的代码中,主线程在任何子线程(通过 start_new_thread 创建的)完成之前就退出了。解决办法是让主线程等到子线程结束再退出。

可以查看讨论 在Python 2.6中使用thread.start_new_thread()的简单线程处理

撰写回答