Python线程计时器,不执行或不立即执行

2024-09-27 00:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现一个线程计时器来控制串行进程的超时。在

def tst_setMaxTimeFlag():

    lock.acquire()
    maxTimeFlag = 1
    lock.release()

    print "timeout!"
    return

def tst_setMaxTimeTimer(maxResponseTime):
    global responseTimer

    lock.acquire()
    maxTimeFlag = 0
    lock.release()

    responseTimer = threading.Timer(2,tst_setMaxTimeFlag)
    print "timer set!"
    responseTimer.start        
    print "timer start!"
    return

我可以想象输出是:

  1. 定时器设置
  2. 定时器启动
  3. 暂停!在

但是,tst嫒setMaxTimeFlag()永远不会被调用和超时!从不打印。在

如果我将responseTimer = threading.Timer(2,tst_setMaxTimeFlag)改为responseTimer = threading.Timer(2,tst_setMaxTimeFlag()),那么不管时间参数是什么,都会立即调用超时函数。在

maxTimeFlag在main中设置为全局,并初始化为0。在

有什么想法吗?在


Tags: lockreleasereturndef线程startprintthreading
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:55

您丢失了代码片段中的所有缩进,因此很难确定您做了什么。在

最明显的问题是responseTimer.start。它只检索start对象的start方法。您需要调用该方法来启动计时器;即do responseTimer.start()。在

然后它将产生您期望的输出,在最后一次“超时”之前有大约2秒的延迟已打印。在

相关问题 更多 >

    热门问题