4

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
4
  • Yes, you can (there's nothing wrong per se with your code), but it'd be better for you explained what you're planning to do with the mutex. A threading.Event might be what you're really looking for. Commented Apr 18, 2022 at 16:21
  • @AKX So. I have some variable and few functions, wich can change value of this variable. That's why I want to write else one function, where I'm going to block mutex before using any function, which can change this variable. And after work changing function I'll unlock mutex. I think such way can solve my problem with changing functions. Commented Apr 18, 2022 at 16:25
  • 1
    I honestly don't understand your description. Also, I don't see why you would want to lock the mutex in one function and then unlock it in another. Generally, you use with to wrap a mutex lock/unlock pair around a so-called critical section of code. Commented Apr 18, 2022 at 17:20
  • @VladimirBait Right - as Ulrich Eckhardt says, you'd want with mutex: variable = ... - only one function can hold the lock with the with block at once. Commented Apr 18, 2022 at 18:20

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.