我有一些与用户通信的程序。当用户输入示例文本时,程序应终止。
import time
import threading
def printer():
while True:
print("Message")
time.sleep(30)
def getter():
while True:
text = str(input())
if text == "sample_text":
print("It's sample text")
thread1 = threading.Thread(target=printer)
thread1.start()
thread2 = threading.Thread(target=getter)
thread2.start()
如何在 getter 函数中终止两个线程
标准方法是使用 threading.Event 对象,并等待它而不是休眠。
import time
import threading
stop = threading.Event()
def printer():
while not stop.is_set():
print("Message")
stop.wait(30)
def getter():
while not stop.is_set():
text = str(input())
if text == "sample_text":
print("It's sample text")
stop.set()
thread1 = threading.Thread(target=printer)
thread1.start()
thread2 = threading.Thread(target=getter)
thread2.start()
thread1.join()
thread2.join()