In the documentation of the threading module it says:
All of the objects provided by this module that have
acquire()
andrelease()
methods can be used as context managers for awith
statement. Theacquire()
method will be called when the block is entered, andrelease()
will be called when the block is exited.
I was wondering if it is called in blocking or non-blocking mode?
A Lock object can not be acquired again by any thread unless it is released by the thread which is accessing the shared resource. An RLock object can be acquired numerous times by any thread. A Lock object can be released by any thread. An RLock object can only be released by the thread which acquired it.
A context manager usually takes care of setting up some resource, e.g. opening a connection, and automatically handles the clean up when we are done with it. Probably, the most common use case is opening a file. The code above will open the file and will keep it open until we are out of the with statement.
A lock can be locked using the acquire() method. Once a thread has acquired the lock, all subsequent attempts to acquire the lock are blocked until it is released. The lock can be released using the release() method. Calling the release() method on a lock, in an unlocked state, results in an error.
From looking at the CPython source, it appears that it's called with default arguments, which means in blocking mode.
The methods you want to look at in particular are __enter__()
, which is called at the beginning of the with
block, and __exit__()
, which is called at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With