线程 - 关闭 while 循环

Threading - close while loop

我有一个 while 循环:

while True:
    x = threading.Timer(3, something)
    x.start()
    # whatever
    x.cancel()

我希望 something 成为一个函数,或者在计时器用完时自动关闭循环的东西。

您可以这样做来取消通用的 while 循环:

global_flag = True
 
def something():
    global_flag = False

while global_flag:
    x = threading.Timer(3, something)
    x.start()
    input("hello! >")
    x.cancel()

因为 threading.Timer 创建了一个线程,你可以做这样的事情来生成一个假的 KeyboardInterrupt 来中断循环:

from time import sleep
import threading
import _thread as thread  # Low-level threading API


def something():
    thread.interrupt_main()  # Raises KeyboardInterrupt.

try:
    while True:
        print('loop iteration started')
        x = threading.Timer(3, something)
        x.start()
        sleep(4)
        x.cancel()
        print('loop iteration completed')
except KeyboardInterrupt:
    print('timeout occurred - loop closed')

print('-fini-')