首页 > 解决方案 > 退出函数不适用于线程方法

问题描述

我需要一些关于我以前在 python 中使用exit()函数的代码的帮助,但今天我尝试使用线程库这是我的代码:

import time
import threading

ts = time.time()
ts_after = ts + 5


def printit():
    global ts_after
    threading.Timer(1.0, printit).start()
    ts1 = time.time()
    if int(ts1) >= int(ts_after):
        print("11")
        exit()
    else:
        pass


printit()

它工作得很好,print("11")也可以工作,但exit()打印后不起作用并继续打印 11

标签: pythonmultithreadingexit

解决方案


在实例上使用该cancel()方法Timer似乎会产生您想要的行为:

import time
import threading

ts = time.time()
ts_after = ts + 5


def printit():
    global ts_after
    my_thread = threading.Timer(1.0, printit)
    my_thread.start()
    ts1 = time.time()
    if int(ts1) >= int(ts_after):
        print("11")
        my_thread.cancel()
    else:
        pass


printit()

cancel()方法只是在实例开始之前停止Timer它。请注意,扩展此代码以便它也可以退出Timer已经启动的对象可能是一个好主意。


推荐阅读