Getting ready

A lock is nothing more than an object that is typically accessible by multiple threads, which a thread must possess before it can proceed to the execution of a protected section of a program. These locks are created by executing the Lock() method, which is defined in the threading module.

Once the lock has been created, we can use two methods that allow us to synchronize the execution of two (or more) threads: the acquire() method to acquire the lock control, and the release() method to release it.

The acquire() method accepts an optional parameter that, if not specified or set to True, forces the thread to suspend its execution until the lock is released and can then be acquired. If, on the other hand, the acquire() method is executed with an argument equal to False, then it immediately returns a Boolean result, which is True if the lock has been acquired, or False otherwise.

In the following example, we show the lock mechanism by modifying the code introduced in the previous recipe, Defining a thread subclass.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.95.38