The effectiveness of locks

With locks, we can turn a shared resource in a concurrent program into a critical section, whose integrity of data is guaranteed to be protected. A critical section guarantees the mutual exclusion of a shared resource, and cannot be accessed concurrently by multiple processes or threads; this will prevent any protected data from being updated or altered with conflicting information, resulting from race conditions.

In the following diagram, Thread B is blocked from accessing the shared resource—the critical section, named var—by a mutex (mutual exclusion) lock, because Thread A is already accessing the resource:

Locks prevent simultaneous access to a critical section

Now, we will specify that, in order to gain access to a critical section in a concurrent program, a thread or process needs to acquire a lock object that is associated with the critical section; similarly, that thread or process also needs to release that lock upon leaving the critical section. This setup will effectively prevent multiple accesses to the critical section, and will therefore prevent race conditions. The following diagram illustrates the execution flow of multiple threads interacting with multiple critical sections, with the implementation of locks in place:

Locks and critical sections in multiple threads

As you can see in the diagram, threads T1 and T2 both interact with three critical sections in their respective execution instructions: CS1, CS2, and CS3. Here, T1 and T2 attempt to access CS1 at almost the same time, and, since CS1 is protected with lock L1, only T1 is able to acquire lock L1, and hence, access/interact with the critical section, while T2 has to spend time waiting for T1 to exit out of the critical section and release the lock before accessing the section itself. Similarly, for the critical sections, CS2 and CS3, although both threads require access to a critical section at the same time, only one can process it, while the other has to wait to acquire the lock associated with the critical section.

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

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