threading.Event() 中的大时间差。在 Python 2 和 3 之间等待

Large time difference in threading.Event().wait between Python 2 and 3

我根据 知道实现 Event().wait 的代码是不同的,但我认为这不应该解释这些时间的巨大差异。

我有一个以 60Hz(每 0.0166666666667s)发送位置数据包的应用程序,接收这些数据包的应用程序正在根据物体速度预测下一个位置。当时间排队时,另一端的对象已经在发送的位置,所以没有位置的视觉跳跃。这发生在 Python 2,但不是 3。Python 3.8.2 在线程中等待发送下一个数据包的时间太长,并且另一个应用程序中的对象已经超出了正在发送的位置。

class taskThread(threading.Thread):

def __init__(self, interval=None):
    '''
    Initializer function:
    interval - The time interval to repeate calls to the 'task' function.
    '''
    super(taskThread, self).__init__()
    self._finished = threading.Event()
    self._interval = float(interval)

def setInterval(self, interval):
    self._interval = float(interval)

def shutdown(self):
    self._finished.set()

def run(self):
    while True:
        if self._finished.isSet():
            return
        tnow = time.time()
        self.task()
        self._finished.wait(self._interval - (time.time() - tnow))
        print(time.time() - tnow)

def task(self):
    '''
    The task function.
    Derived classes must implement this function.
    '''
    raise Exception('Task must be implemented!')

def __enter__(self):
    self.start()
    return self

def __exit__(self, type, value, traceback):
    self.shutdown()
    return True

Python 2.7.0 始终打印:

0.0169999599457
0.0169999599457
0.0170001983643
0.0169999599457
0.0169999599457
0.0169999599457
0.0169999599457
0.0169999599457

Python 3.8.2 等待更长的时间

0.031026363372802734
0.0320279598236084
0.031026363372802734
0.031026840209960938
0.031527042388916016
0.031026601791381836
0.03103041648864746
0.03302431106567383

我对 Python 3 做错了什么吗?

这是一个已知错误:

https://bugs.python.org/issue41299

由于没有当前的解决方案,我使用 time.sleep() 代替。