Adrian Muljadi
Adrian Muljadi

Reputation: 168

Lock with timeout in Python2.7

The accepted solution here doesn't work for all situations,

How to implement a Lock with a timeout in Python 2.7

(In particular the last thread who owns the lock calls cond.notify() when no one holds the conditional variable)

Then, I've tried a spin lock like this:

import threading
import time

class TimeLock(object):

    def __init__(self):
        self._lock = threading.Lock()


    def acquire_lock(self, timeout = 0):
        ''' If timeout = 0, do a blocking lock
            else, return False at [timeout] seconds
        '''
        if timeout == 0:
            return self._lock.acquire()   # Block for the lock

        current_time = start_time = time.time()
        while current_time < start_time + timeout:
            if self._lock.acquire(False): # Contend for the lock, without blocking
                return True
            else:
                time.sleep(1)
                current_time = time.time()

        # Time out
        return False

    def release_lock(self):
        self._lock.release()  

However after trying, the spin lock will almost always starve against the blocking lock. Is there other solutions?

Upvotes: 2

Views: 1514

Answers (1)

Adrian Muljadi
Adrian Muljadi

Reputation: 168

Turns out that python queues have a timeout feature in their Queue module in 2.7

I can simulate a lock with time out by doing this

lock.acquire() -> Queue.get(block=True, timeout=timeout)
lock.release() -> Queue.put(1, block=False)

Upvotes: 3

Related Questions