Synchronization & Concurrency

Answer & solution
Official answer: A; B; D
Serially completing all five operations gives counter=5, proving A. For B, let one thread acquire two permits and read counter=0, then pause before writing. The other four can each acquire two of the remaining three permits, increment and finish sequentially. Finally the paused thread writes its stale result 1 and finishes. C cannot occur after successful completion: every write is a nonnegative value read plus one, so the final write is at least 1. For D, let each of the five threads acquire its first permit before any acquires a second. All then block on the second wait with no permit left and none able to signal. These are pseudocode read-modify-write interleavings, as explicitly assumed.
The semaphore limits simultaneous holders of permits but does not provide mutual exclusion for counter++: two threads can each hold two permits out of five. For final value 1, the crucial schedule is a delayed stale write from the first thread after the other four have successively completed. For deadlock, no thread reaches its first signal because every thread is stuck on its second wait. Replacing the two waits by one atomic acquisition of two permits would remove that particular hold-and-wait pattern, but that is not the given code.