135 views
0 votes
0 votes
bool p1_in_crit_sect = false;
bool p2_in_crit_sect = false;

while (true) {
    while (p2_in_crit_sect == true)
        ; /* do nothing */
    
    p1_in_crit_sect = true;
    
    /* ... critical section ... */

    p1_in_crit_sect = false;
}

while (true) {
    while (p1_in_crit_sect == true)
        ; /* do nothing */

    p2_in_crit_sect = true;
    
    /* ... critical section ... */

    p2_in_crit_sect = false;
}
is mutual exclusion satisfied?

1 Answer

1 votes
1 votes

Your code does not ensure mutual exclusion. It uses a basic form of a spinlock, but there is a race condition that could lead to both processes (p1_in_crit_sect and p2_in_crit_sect) being in their critical sections simultaneously.

Consider the following interleaving of operations:

  1. Process 1 enters its outer loop and checks p2_in_crit_sect, which is false, so it enters the critical section.
  2. Process 2 enters its outer loop and checks p1_in_crit_sect, which is false, so it enters the critical section.
  3. Now, both Process 1 and Process 2 are in their critical sections simultaneously, violating mutual exclusion.

To achieve mutual exclusion, you typically need to use some form of synchronization, such as locks or semaphores. Spinlocks, as shown in your code, are a simple form of synchronization, but they need to be carefully implemented to avoid race conditions. In this case, additional measures like using atomic operations or a more advanced synchronization mechanism would be needed to ensure mutual exclusion.

Related questions

400
views
1 answers
0 votes
N3314nch41 asked Sep 10, 2023
400 views
How to approach synchronization (specifically semaphore) question, there size are really intimidating and i’m unable to decode the code written? What to do??