【问题标题】:Pythn Timer prints in the middle of other prints. Is there some issue with execution order?Python Timer 打印在其他打印的中间。执行顺序有问题吗?
【发布时间】:2021-09-22 13:43:29
【问题描述】:

我正在测试计时器功能,我得到了一些奇怪的打印。我关心的是这是否是代码实际执行的方式,即函数再次运行,而前一次迭代没有完成,因此它可能会弄乱代码。还是只是打印问题,代码本身没问题?

import time
import threading
from TestTimerObject import TimerObject

def TestTimers():

    timers = []

    for x in range(10):
        new_timer_obj = TimerObject("Timer" + str(x))
        new_timer_obj.timer = threading.Timer(10.0, TimerFinished, [x])
        new_timer_obj.timer.start()

def TimerFinished(param):
    print("Finished ", param)


TestTimers()

打印:

Finished  0
Finished  3
Finished  1
Finished  2
Finished Finished  4
Finished  5Finished  8
Finished  9
 6
Finished  7

希望我的问题不会令人困惑。简单来说,为什么我要打印这个烂摊子而不是这样的东西(顺序无关紧要)

Finished 0
Finished 3 
Finished 1 
Finished 2 
Finished 4 
Finished 5 
Finished 8 
Finished 9 
Finished 6 
Finished 7

【问题讨论】:

标签: python


【解决方案1】:

您遇到了问题,因为计时器在不同的线程中执行。您应该使用模块的信号量实现来确保正确同步。

import time
import threading
from TestTimerObject import TimerObject

sem = threading.Semaphore(value=1)

def TestTimers():

    timers = []

    for x in range(10):
        new_timer_obj = TimerObject("Timer" + str(x))
        new_timer_obj.timer = threading.Timer(10.0, TimerFinished, [x])
        new_timer_obj.timer.start()

def TimerFinished(param):
    sem.aquire()
    print("Finished ", param)
    sem.release()


TestTimers() 

【讨论】:

  • 太棒了,解决了这个问题,不知道这存在。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多