如何在 1 个函数中停止 2 个线程

问题描述 投票:0回答:1

我有一些与用户通信的程序。当用户输入示例文本时,程序应终止。

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 函数中终止两个线程

python multithreading python-multithreading
1个回答
0
投票

标准方法是使用 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()
© www.soinside.com 2019 - 2024. All rights reserved.