当前位置: 代码迷 >> 综合 >> Python多线程 坑Unhandled exception in thread started by Error in sys.excepthook
  详细解决方案

Python多线程 坑Unhandled exception in thread started by Error in sys.excepthook

热度:84   发布时间:2023-12-28 13:26:06.0

先给大家推荐翻滚吧挨踢男的博客Python菜鸟学习手册15----多线程写的又有趣又易于理解

第一个demo我就踩了一次坑:

def foo(tag, delay):count = 0while count < 5:time.sleep(delay)count += 1print("%s:%s" % (tag, time.ctime(time.time())))try:_thread.start_new_thread(foo, ("thread1", 2))_thread.start_new_thread(foo, ("thread2", 5))except:print("error")

报错了Unhandled exception in thread started by Error in sys.excepthook

然后网友们说在try最后面加个延时函数time.sleep(3)。但是只打印了两个。这是为什么呢?

首先我们先分析一下,为什么最后要加一个sleep?time.sleep(delay)是子线程来执行的,就是我们新建thread1和thread2。而我们的主线程执行的就是try后面加的time.sleep(3)。故事是这样的,在某一天,主线程被命令睡觉了,然后它睡了一会,然后醒来发现他该去死了,然后主线程就去死了,子线程看见主线程死了,悲痛欲绝,“MD我也不活了”,两个子线程也去死了。他们都死光后留下了一个错误“Unhandled exception in thread started by Error in sys.excepthook”而且只打印了两个信息。

聪明的网友们为了让子线程得以打印信息就挖了一个坑给主线程:

在整个程序最后面添加:

while(1):pass

这个坑太深主线程不能跳出来,只能由码农们强制终止程序,但也成功避免了主程序去死。在java里面sleep是不会交出CPU使用权,在python里面呢?在看过知乎大牛们的看法。

Python中的多线程只能利用单核,不交出使用权大家都是用不了。

  相关解决方案