解决pycharm运行多线程程序报错"Unhandled exception in thread started by sys.excepthook is missing"

运行报错实例代码:

import time
import thread


def timer(no, interval):
    cnt = 0
    while cnt < 3:
        print 'Thread:(%d) Time:%s\n' % (no, time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit_thread()


def test():  # Use thread.start_new_thread() to create 2 new threads
    thread.start_new_thread(timer, (1, 1))
    thread.start_new_thread(timer, (2, 2))


if __name__ == '__main__':
    test()

使用pyCharm运行后报错:

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



问题原因:启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常 。


问题解决方法:

在test()后增加sleep,保证子线程结束后主线程才结束。


解决问题后代码:

import time
import thread


def timer(no, interval):
    cnt = 0
    while cnt < 3:
        print 'Thread:(%d) Time:%s\n' % (no, time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit_thread()


def test():  # Use thread.start_new_thread() to create 2 new threads
    thread.start_new_thread(timer, (1, 1))
    thread.start_new_thread(timer, (2, 2))


if __name__ == '__main__':
    test()
    time.sleep(30)

运行结果:



猜你喜欢

转载自blog.csdn.net/HJULKK/article/details/52388800