在Python 3.5中使用事件结束循环线程
我在停止循环线程时遇到问题。我使用事件来停止循环,但输出与我预期的不同。我编写了以下代码在Python 3.5中使用事件结束循环线程,python,multithreading,events,python-multithreading,Python,Multithreading,Events,Python Multithreading,我在停止循环线程时遇到问题。我使用事件来停止循环,但输出与我预期的不同。我编写了以下代码 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):
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循环结束时,“done”一词会再次打印出来。但由于某些原因,“完成”会打印两次。我使用的事件是错误的还是线程启动了多次?缺少两点:
在prgm=bar之前添加如果uuuuu name_uuuuuuuuu=='uuuuuuu main
每次运行前添加sleep0.1A。。。
您已经在bar的构造函数(即bar)中执行self.run\u线程。\uuu init\uuu:
因此,在创建bar实例时:
您正在执行bar.run\u线程。当前代码执行此函数两次:
结果,你会有一些意想不到的行为 我在线程内部添加了printhallo'之前。输出打印两次hallo。因此,由于某些原因,线程启动了两次。添加if name==“main”:如何改进代码?除了改进code.Oops的总体“设计”之外。谢谢你的回答
class bar(...):
def __init__(self):
threading.Thread.__init__(self)
# !!!!
self.run_thread()
stuff = bar()
prgm = bar() # executed here
prgm.run_thread() # and here