Suppose we want to synchronize two concurrent processes and using binary semaphores and . The code for the processes and is shown below.
Synchronization statements can be inserted only at points and
Which of the following will ensure that the output string never contains a substring of the form and where is odd?
View worked solution
Answer: C
To prevent the output string from containing substrings of the form and where is odd, we must ensure that any sequence of consecutive s (sandwiched between s) and any sequence of consecutive s (sandwiched between s) always has an even length.
Analyzing Option C:
- Synchronization setup:
- at and at
- at and at
- is a binary semaphore initialized to .
- Effect: Since both processes compete for the same semaphore at the beginning of their loops ( and ) and release it only at the end ( and ), the critical sections are mutually exclusive.
- This means once process starts executing, it cannot be interleaved by until it finishes printing both s. Similarly, cannot be interleaved by until it finishes printing both s.
- Thus, the characters and are always printed in atomic blocks of "00" and "11" respectively.
- Any output sequence will be a combination of these blocks, such as:
- In any such sequence, the number of consecutive s or s is always a multiple of (even). Hence, can never be odd, which satisfies the requirement.
Eliminating Other Options:
- Options A, B, and D: These options use two different semaphores ( and ) initialized to . This allows both processes and to enter their loops simultaneously. Their print statements can interleave, leading to sequences like (where , which is odd).
Therefore, C is the correct option.
Free practice · Your answers on this page are not saved.
