pythonmultithreadinglocking

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.


Solution

  • 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