379 views
0 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 1 vote

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.

Position:
Show:

Related questions

3 3 votes
1 1 answer
207
207 views
GO Classes asked Aug 3
207 views
Which of the following statements are correct?In the standard reader-preference solution, the first reader executes $\texttt{wait(wrt)}$. In the standard reader-preferenc...
2 2 votes
2 2 answers
181
181 views
GO Classes asked Jul 29
181 views
Which of the following is the correct order of semaphore operations for a producer?$\texttt{wait(mutex)}$, $\texttt{wait(empty)}$, insert item, $\texttt{signal(full)}$, $...
3 3 votes
1 1 answer
250
250 views
GO Classes asked Jul 25
250 views
Which of the following statements are correct?Mutual exclusion ensures that if one process is executing in its critical section, no other process can execute in its criti...
2 2 votes
3 3 answers
319
319 views