PyCharm中Unhandled exception in thread started by Error in sys.excepthook问题解决

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Megustas_JJC/article/details/79047761
#-*-coding: utf-8 -*-
import thread
import time
#定义线程函数
def print_time(threadName,delay):
    count = 0
    while count<5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName,time.ctime(time.time()))
#创建两个线程
def test():
    thread.start_new_thread(print_time, ("Thread-1", 1,))
    thread.start_new_thread(print_time, ("Thread-2", 2,))
if __name__=="__main__":
    test()

这里写图片描述
问题原因:
启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常 。如下想出两种解决方式:

(1)通过主线程sleep等待的方式

#-*-coding: utf-8 -*-
import thread
import time
#定义线程函数
def print_time(threadName,delay):
    count = 0
    while count<5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName,time.ctime(time.time()))
#创建两个线程
def test():
    thread.start_new_thread(print_time, ("Thread-1", 1,))
    thread.start_new_thread(print_time, ("Thread-2", 2,))
if __name__=="__main__":
    test()
    """
    防止Unhandled exception in thread started by Error in sys.excepthook问题。
    """
    time.sleep(30)

thread.start_new_thread() 去创建线程的话,要保证在主线程结束之前,小线程要执行完毕,否则会出现如上错误,因此往往改用threading模块。

(2)使用标志位,不过效率比较低,代码风格也不好,这个相当于自旋锁

#-*-coding: utf-8 -*-
import thread
import time
#定义线程函数
def print_time0(threadName,delay,sign):
    count = 0
    while count<5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName,time.ctime(time.time()))
    sign[0] = True
def print_time1(threadName,delay,sign):
    count = 0
    while count<5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName,time.ctime(time.time()))
    sign[1] = True
#创建两个线程
def test():
    sign=[False,False]
    thread.start_new_thread(print_time0, ("Thread-1", 1,sign))
    thread.start_new_thread(print_time1, ("Thread-2", 2,sign))
    while not all(sign):pass
    print "all Done at",time.ctime()
if __name__=="__main__":
    test()



用threading模块的join函数可以检测线程是否结束,因此使用threading模块可以更好的解决。

猜你喜欢

转载自blog.csdn.net/Megustas_JJC/article/details/79047761
今日推荐