Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.13 Threading lock.acquire vs lock.acquire_lock

In Python 3.13 (haven't checked lower versions) there seem to be two locking mechanisms for the threading.Lock class. I've looked online but found no mentions of acquire_lock or release_lock and wanted to ask if anyone knows what the difference is between them and the standard acquire and release methods.

Here's the threading.Lock class for reference. The methods are commented as undocumented:

class Lock:
    def __enter__(self) -> bool: ...
    def __exit__(
        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
    ) -> None: ...
    def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ...
    def release(self) -> None: ...
    def locked(self) -> bool: ...
    def acquire_lock(self, blocking: bool = ..., timeout: float = ...) -> bool: ...  # undocumented
    def release_lock(self) -> None: ...  # undocumented
    def locked_lock(self) -> bool: ...  # undocumented

Just curious whether there's a difference between the call lock.acquire_lock and lock.acquire or whether this is merely a name-change that will take effect in the future.

like image 866
leolion3 Avatar asked Aug 09 '26 23:08

leolion3


1 Answers

currently, they are just aliases, and according to github history they have been like that for the past 15 years, you shouldn't be using undocumented functions, they can be removed at any time.

    {"acquire_lock", _PyCFunction_CAST(lock_PyThread_acquire_lock),
    ...
    {"acquire",      _PyCFunction_CAST(lock_PyThread_acquire_lock),
    ...
    {"release_lock", lock_PyThread_release_lock,
    ...
    {"release",      lock_PyThread_release_lock,

the best thing to do is not use any of the 4 functions anyway, instead use a with block to properly lock and release the lock when an exception is thrown.

some_lock = Lock()
with some_lock:
    # code protected by lock here
    # lock released when exception is thrown
like image 154
Ahmed AEK Avatar answered Aug 12 '26 13:08

Ahmed AEK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!