python中的线程遇到了麻烦

时间:2014-01-15 16:34:23

标签: python multithreading

我为线程编写了非常基本的python代码......

import time
import thread

def print_hello(name,delay):
    while 1:
        print name
        time.sleep(delay)

        try:
            thread.start_new_thread(print_hello, ("frist",1,))
            thread.start_new_thread(print_hello, ("second",2,))
        except:
            print "unable to start thread"

        time.sleep(4)
        print "hello"

输出是:

second
frist
frist
second
frist
frist
hello

例外:

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

我的查询是:

  1. 为什么第二次来1?
  2. 为什么例外?

2 个答案:

答案 0 :(得分:3)

简单回答:因为线程很棘手。

归零,上面输入的代码不可能产生你显示的输出。我认为你真正想要的是从try:向下延伸到与def相同的水平。当我进行更改并运行您的代码时,我会得到与您类似的结果,有时

解决你的第一个问题:Frist排在第二位,因为time.sleep()并不能保证它会在指定的时间内延迟。请参阅文档here。 当我运行你的代码时,有时frist排在第二位,有时frist首先出现,有时它们会一起出现。

解决你的第二个问题:因为你的两个背景线程在主程序退出时将地毯拉出来。

当主程序执行sleepprint时,两个线程运行正常。完成后,程序会尝试退出。大约在同一时间,两个线程正在尝试打印它们的输出。

我发现如果你将sleep(4)增加到sleep(5.5)它运行得更清晰,因为当程序退出时,两个线程都没有尝试print

在现实生活中你应该做的是有一种机制来指示后台线程突破其infinte循环并在主程序退出之前退出,然后让主程序等待(通过调用join())直到线程在退出之前已经停止。

了解threadingjoin

答案 1 :(得分:1)

这是一个无限循环。

print_hello函数启动一个线程,该线程启动一个启动线程的线程......

糟糕的事情会发生,最终会崩溃。