Home > Software engineering >  Mutex lock in python3
Mutex lock in python3

Time:04-20

I'm using mutex for blocking part of code in the first function. Can I unlock mutex in the second function? For example:

import threading

mutex = threading.Lock()

def function1():
    mutex.acquire()
    #do something

def function2():
    #do something
    mutex.release()
    #do something

CodePudding user response:

You certainly can do what you're asking, locking the mutex in one function and unlocking it in another one. But you probably shouldn't. It's bad design. If the code that uses those functions calls them in the wrong order, the mutex may be locked and never unlocked, or be unlocked when it isn't locked (or even worse, when it's locked by a different thread). If you can only ever call the functions in exactly one order, why are they even separate functions?

A better idea may be to move the lock-handling code out of the functions and make the caller responsible for locking and unlocking. Then you can use a with statement that ensures the lock and unlock are exactly paired up, even in the face of exceptions or other unexpected behavior.

with mutex:
    function1()
    function2()

Or if not all parts of the two functions are "hot" and need the lock held to ensure they run correctly, you might consider factoring out the parts that need the lock into a third function that runs in between the other two:

function1_cold_parts()
with mutex:
    hot_parts()
function2_cold_parts()
  • Related