【问题标题】:Ending a looping thread using Events in Python 3.5在 Python 3.5 中使用事件结束循环线程
【发布时间】:2017-03-23 19:40:09
【问题描述】:

我无法停止循环线程。我使用一个事件来停止循环,但输出与我预期的不同。我写了以下代码

import threading 
from time import sleep

class foo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.stop_event = threading.Event()

    def run(self):
        while not self.stop_event.is_set():
            print('1')
            sleep(1)
            print('2')
            sleep(1)
        print('done')

class bar(threading.Thread):
    def __init__(self):
       threading.Thread.__init__(self)
       self.run_thread()


    def run_thread(self):
       th1 = foo()
       th1.start()
       sleep(4)
       th1.stop_event.set()

prgm = bar()
prgm.run_thread()

给我输出:

1
2
1
2
1
done
2
1
2
done

我希望在 while 循环结束时打印一次“完成”这个词。但由于某种原因,“完成”被打印了两次。是我用错了事件还是线程启动了多次?

【问题讨论】:

  • 我在 while 之前添加了 print(''hallo') (在线程内)。输出打印“你好”两次。所以由于某种原因线程启动了两次。

标签: python multithreading events python-multithreading


【解决方案1】:

你已经在bar的构造函数中做了self.run_thread()(即bar.__init__):

class bar(...):
    def __init__(self):
       threading.Thread.__init__(self)

       # !!!!
       self.run_thread()

所以,当您创建bar 的实例时:

stuff = bar()

也在执行bar.run_thread。您当前的代码执行此函数两次

prgm = bar() # executed here
prgm.run_thread() # and here

因此,您会得到一些意想不到的行为。

【讨论】:

  • 糟糕。感谢您的回答
【解决方案2】:

漏掉两点:

  1. prgm = bar() 之前添加if __name__ == '__main__':
  2. 在每个run... 之前添加sleep(0.1)A

【讨论】:

  • 添加“if name == 'main':”会如何改进代码?除了改进代码的整体“设计”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2012-06-08
  • 1970-01-01
  • 2014-06-10
  • 2016-06-06
相关资源
最近更新 更多