Search code examples
pythonlockingpython-multithreading

How can another Python thread wait until a lock is released?


Given this code, how can I make sure that get_model() can always be called without waiting, unless reload_lock is active?

Preferably, I don't want get_model() to aquire the reload_lock itself, as all threads may freely call this method unless the application is reloading it's models.

import threading

reload_lock = threading.Lock()


def get_model(name):
    # Normally this can be called, unless reload_models() is active
    # e.g. "if reload_lock.locked() -> wait until lock is released.
    ...


def reload_models():
    try:
        reload_lock.acquire()
        ...  # reload models
    finally:
        reload_lock.release()

Solution

  • Maybe you should try like this, in the get_model():

    if reload_lock.locked():
        reload_lock.acquire()
        reload_lock.release()
    

    I know it's an acquire, but can be a solution if you instantly release it.