Why must the Compareandswap instruction be implemented in an
Why must the Compare_and_swap instruction be implemented in an atomic manner?
2) How does Peterson\'s Algorithm avoid starvation? Explain.
Solution
1. Atomicity is used in cases to prevent concurrent access or execution of a particular resource or code or variable by multiple threads at the same time in an multithreaded environment.
Compare and swap acts in considering compare and act pattern. The check then act pattern occurs when the code first checks the value of a variable and then acts based on that value.
Example
In the above code, in case of multiple thread running or accessing the same lock, then if synchronization is not applied then multiple threads may access the same unmodified boolean value of the lock which is wrong.
In compare and swap, to make it atomic, the lock() method compares the variable lock_applied to the expected value false and if lock_applied is equal to this expected value, it swaps the variable\'s value to true and thus preventing unmodified access for multiple threads.
2. Peterson\'s algorithm for mutual exclusion allows for 2 processes to share a single-use resource without conflict by using shared memory.
The algorithm uses two variables flag and turn based in which the entry into the critical section of a resource is monitored.
For processes P1 and P2, flag[P1] = true indicates it wants to enter the critical section and it is guaranteed by process P2 setting it\'s value of turn to 0, ie, turn[P2] = 0, which indicates P2 has given priority to P1 ahead of itself.
