Search code examples
pythoneventswait

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


I know based on this link that the code to implement the Event().wait is different, but I do not think that should account for the large difference in these times.

I have an application that sends positional packets at 60Hz (every 0.0166666666667s), the application receiving these packets is predicting the next positions based on the objects velocity. When the timing lines up, the object on the other end is already at the position being sent, so there is no visual jump in position. This occurs in Python 2, but not 3. Python 3.8.2 is waiting too long to send the next packet in the thread, and the object in the other application has over shot the position being sent.

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 consistently prints :

0.0169999599457
0.0169999599457
0.0170001983643
0.0169999599457
0.0169999599457
0.0169999599457
0.0169999599457
0.0169999599457

Python 3.8.2 waits much longer

0.031026363372802734
0.0320279598236084
0.031026363372802734
0.031026840209960938
0.031527042388916016
0.031026601791381836
0.03103041648864746
0.03302431106567383

Am I doing something incorrectly for Python 3?


Solution

  • This is a known bug:

    https://bugs.python.org/issue41299

    With no current solution, I used time.sleep() instead.