Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using threading.Lock as context manager

In the documentation of the threading module it says:

All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement. The acquire() method will be called when the block is entered, and release() will be called when the block is exited.

I was wondering if it is called in blocking or non-blocking mode?

like image 376
P3trus Avatar asked Nov 08 '12 13:11

P3trus


People also ask

What is the difference between threading lock and threading RLock?

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.

When would you use a context manager?

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.

How does Python thread lock work?

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.


1 Answers

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.

like image 140
Sam Mussmann Avatar answered Sep 28 '22 07:09

Sam Mussmann