简体   繁体   English

python不会创建线程?

[英]python won't create thread?

I might be missing something silly, but ive ran my code in pythonwin and it works, but when I run it in command-line it freaks 我可能会遗漏一些愚蠢的东西,但是我已经在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

The exception happens when the main thread (the one that starts other threads) finishes. 当主线程(启动其他线程的线程)完成时发生异常。 In your code the main thread quits before any of your sub threads (created by start_new_thread ) finish. 在您的代码中,主线程在任何子线程(由start_new_thread创建)完成之前退出。 The solution is to wait at your main thread till the child threads ends. 解决方案是在主线程处等待,直到子线程结束。

See the discussion Simple threading in Python 2.6 using thread.start_new_thread() 请参阅讨论使用thread.start_new_thread()在Python 2.6中进行简单线程化

It is because the main thread ends, and as you use thread insted of threading , the "child threads" die as well. 这是因为主线程结束,并且当你使用thread插入threading ,“子线程”也会死掉。

Better use the module threading . 更好地使用模块threading

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

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