Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python time.time() reliability in concurrent programs

I'm writing a simulation for a token ring LAN and trying to run a timer in a separate thread to my main program to check for a time out on receiving an "alive status" from the monitor. I'm starting the monitor program before the other nodes and they both have the same wait time before either sending and "alive status" or a starting to elect a new monitor but the node program seems to time out before the monitor.

Is this just a problem with concurrency in python or is it more likely a problem with my code?

Here is the function that the thread runs, if you need more info just ask

def timer():
    global reset
    global ismonitor
    global mToSend
    global dataToSend
    reset = time.time()
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    while 1:
        timer = time.time()
        elapsed = timer - reset
        if elapsed > 5:
            if ismonitor:
                mToSend = "110000" ## send around a token with a monitor alive flag on the broadcast channel
                mToSend += maddr
                dataToSend = True
                reset = time.time()
            else:
                holdelection()
                reset = time.time()
like image 961
Cob50nm Avatar asked Nov 04 '22 01:11

Cob50nm


1 Answers

Due to Python's global interpreter lock (GIL) threads are never executed simultaneously. Instead, one thread gets a slice of execution time while all the other threads are locked (they are not executing any code). That's why a call to time.time() is only as accurate as the minimal time slice assigned to a thread.

Have a look at the work of David Beazley to gain a better understanding how threading works in Python: http://www.dabeaz.com/GIL/ He shows that depending on the version of Python you use threads can be blocked for seconds before they can reacquire the GIL. In that case your time.time() call would be off by an equal amount of time.

If you want higher accuracy you should consider using processes instead of threads. They are not more complex to use than threads in Python with the help of the multiprocessing module: http://docs.python.org/3.3/library/multiprocessing.html

like image 189
Bernhard Kausler Avatar answered Nov 15 '22 05:11

Bernhard Kausler