【发布时间】: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