如何在线程中尽早终止循环?

How to terminate a loop early in in a thread?

我有一个循环,它向网络服务发出获取请求以获取数据并做一些事情,但我想 'manually' 终止 thread/event,这是我通过以下示例实现的:

from threading import Event

exit = Event()

if external_condition():
    exit.set()

for _ in range(mins):
    fetch_data_and_do_stuff()
    exit.wait(10) #wait 10 seconds

因此,唯一终止它的是循环之间的睡眠时间。我怎样才能终止循环,使其在到达最后一次迭代之前不会保持 运行?

nvm 我是这样解决的

from threading import Event

exit = Event()

if external_condition():
    exit.set()

for _ in range(mins):
    fetch_data_and_do_stuff()
    if exit.wait(10):
         break

条件 returns 被杀死时为真,并且还会休眠 10 秒,所以它有效

你有 2 个选择, 完全杀死线程或进程 或使循环的布尔值为假。走那条路 你可以这样使用一个全局变量: [Python 3.7] , 运行 it to see

from threading import Thread
from time import sleep

global glob
glob=True

def threaded_function():
    
    while glob:
        print("\n [Thread] this thread is running until main function halts this")
        sleep(0.8)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = ())
    thread.start()

    for i in range(4,0,-1):
        print("\n [Main] thread will be terminated in "+str(i)+" seconds")
        sleep(1)
    
    glob=False
    
    while True:
        print("[Main] program is over")
        sleep(1)