【问题标题】:Threads in python facing trouble [closed]python中的线程面临麻烦[关闭]
【发布时间】:2014-01-15 16:34:22
【问题描述】:

我已经为线程编写了非常基本的 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. 为什么第二次来第一次?
  2. 为什么会出现异常?

【问题讨论】:

  • 有些人在遇到问题时会想“我会使用线程”。然后两个他们有问题。

标签: python multithreading


【解决方案1】:

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

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

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

解决您的第二个问题:因为当主程序退出时,您的两个后台线程会从它们下面拉出地毯。

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

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

在现实生活中你应该做的是有一个机制来通知后台线程在主程序退出之前退出它们的无限循环并退出,然后让主程序等待(通过调用join())直到线程退出前已停止。

了解threadingjoin

【讨论】:

  • 你好,我是线程程序的新手。我明白了这一点,但我也有一些基本的查询线程实际上是如何工作的?是不是所有线程都分配给了一个单独的堆栈,我很惊讶为什么一旦程序执行停止线程就会停止。
  • @user2743375 我不太了解内部细节。也许这个问题 (stackoverflow.com/questions/31340/…) 会有所帮助。
  • +1 一致地使用“frist”:D
【解决方案2】:

这是一个无限循环。

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

坏事会发生,最终会崩溃。

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多