GATE CSE has asked 55 questions on Synchronization & Concurrency (Operating Systems) from 1991 to 2026, in 33 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 0.9 marks per 100-mark paper on average, against 1.3 since 2003. Since 2014 the questions have been 9 MCQ, 3 NAT and 2 MSQ. 13 groups of questions here are solved the same way; “One per method” keeps the newest of each.
Three processes each execute: wait(A); print(*); X=X+1; if X==2 then {print($); signal(B);}; signal(A); wait(B); print(#); signal(B). Binary semaphores start A=1,B=0 and shared X=0. Each line is atomic. Which outputs are possible? A **$*###; B **$#*##; C **$##*#; D ***$###.
Select all that apply
Answer & solution
Official answer: A, B, C
Givens and goal
Three processes each execute: wait(A); print(*); X=X+1; if X==2 then {print($); signal(B);}; signal(A); wait(B); print(#); signal(B). Binary semaphores start A=1,B=0 and shared X=0. Each line is atomic. Which outputs are possible? A $*###; B **$#*##; C **$##*#; D *$###.
Approach
Find invariant ordering constraints, then exhibit schedules achieving each candidate.
Step-by-step solution
1. A protects the star and increment section. The first entrant prints a star and changes X from 0 to 1. The second prints another star and changes X to 2, then prints $ before releasing A. 2. The third entrant cannot print its star until that release. Therefore the dollar must occur immediately after the second star among these star/dollar events, and ***$### is impossible. Preempting the second process before $ does not help: it still holds A. 3. B initially blocks all hash printing. It is first signaled only after the dollar; each process that prints a hash then signals B for another. Thus no hash can precede $, while each process’s own star must precede its hash. 4. For A, let the first two processes complete their A sections, then let the third complete its A section before allowing any hash sections. For B, after the first two A sections allow one of those processes to print a hash, then allow the third star, then the remaining hashes. 5. For C, let both first and second processes print their hashes after $, delaying the third A section until afterward. The third then prints its star followed by its hash. These realize all A,B,C exactly. 6. Therefore select A,B,C. The invariant and the explicit schedules together establish both impossibility and feasibility; a single simulated scheduling order would not suffice.
Initially a=b=1. Thread T1 performs a=a+1 followed by b=b+1. Thread T2 performs b=2*b followed by a=2*a. Each assignment is atomic, but threads may interleave. Which set lists every possible final (a,b)? A {(4,4),(3,3),(4,3)}; B {(3,4),(4,3),(3,3)}; C {(4,4),(4,3),(3,4)}; D {(2,2),(2,3),(3,4)}.
Your answer
Answer & solution
Official answer: A
Approach: Preserve each thread's internal order while allowing every merge of the two two-statement sequences. 1. Label T1's statements A: increment a, B: increment b; label T2's statements C: double b, D: double a. Legal interleavings satisfy A before B and C before D. 2. There are six such orders: ABCD gives (4,4); ACBD gives (4,3); ACDB gives (4,3); CABD gives (4,3); CADB gives (4,3); CDAB gives (3,3). For example, ABCD increments each initial 1 to 2 before doubling it to 4. 3. Removing duplicates leaves {(4,4),(4,3),(3,3)}. 4. To see why (3,4) is impossible, a=3 would require D before A, while b=4 would require B before C. Together with the thread orders this demands C<D<A<B<C, an impossible cycle. Answer: A. Atomic assignments prevent lost updates inside an assignment, but do not force a whole thread to run as one unit.
Shared X starts at 10. Five threads each do wait(s); X=X+1; signal(s), and three do wait(s); X=X−1; signal(s). The updates are non-atomic read/modify/write operations. Find minimum final values V1,V2 for a binary semaphore initially 1 and a counting semaphore initially 2. A 15,7; B 7,7; C 12,7; D 12,8.
Your answer
Answer & solution
Official answer: C
With binary semaphore1 the updates are mutually exclusive: V1=10+5−3=12. With counting semaphore2, two updates may overlap. For a witness to V2=7, let one decrement enter and read 10, then pause before its write. Through the second permit run all five increments to completion. Resume the held decrement to overwrite X with 9, then run the other two decrements serially, giving 8 then 7. No value below 7 can arise because a value’s chain of read/write dependencies starts at 10 and contains at most the three decrement operations; increments only increase it. Thus12, 7, option C, under the intended non-atomic read-modify-write interleaving model.
Teaching detail. A semaphore with capacity two limits concurrency but does not make each arithmetic assignment atomic. Two threads can read the same old value and later overwrite each other's results. The witness yielding 7 uses only two simultaneous entrants at any moment: one delayed decrement occupies one permit while all other selected operations use the second. The lower-bound argument follows the ancestry of the final written value, not the total number of writes. Each decrement in that ancestry contributes −1 once at most, and there are only three decrements available.
Three infinite threads run on one CPU with binary semaphores. T1 repeats wait(S3); print C; signal(S2). T2 repeats wait(S1); print B; signal(S3). T3 repeats wait(S2); print A; signal(S1). Which initialization forces BCABC… despite arbitrary context switches? A (S1,S2,S3)=(1,1,1); B (1,1,0); C (1,0,0); D (0,1,1).
Your answer
Answer & solution
Official answer: C
T2 waits on S1 and prints B, then signals S3. T1 waits on S3 and prints C, then signals S2. T3 waits on S2 and prints A, then signals S1. Initialize only S1 to 1, with S2=S3=0, to force B→C→A repeatedly. That is C. This assumes ordinary successful semaphore operations and eventual scheduling of enabled threads.
Track the unique token: (1,0,0) enables only T2. Its wait consumes S1 and its signal creates the S3 token; then T1 creates S2; then T3 restores S1. Context switching can delay progress, but cannot permit a different letter while its semaphore is zero.
Shared counter=0 and counting semaphore S=5. Five threads concurrently execute parop(){wait(S); wait(S); counter++; signal(S); signal(S);} The increment is explicitly non-atomic. Select possible outcomes: A counter=5 after all complete; B counter=1 after all complete; C counter=0 after all complete; D all five threads deadlock.
Select all that apply
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.
Each of n processes runs this once, with shared count=0, semaphores a=1,b=0, and P not using count: P; wait(a); count=count+1; if(count==n) signal(b); signal(a); wait(b); signal(b); Q; What is guaranteed? A no Q before all P finish; B at most two in Q; C P mutually exclusive; D at most n−1 in P.
Your answer
Answer & solution
Official answer: A
Worked explanation
Before any process can signal b, some process must observe count=n while holding a. Since increments are protected and occur after P, count is exactly the number of completed P sections that have passed the increment. Thus the first b signal proves every P has completed. The subsequent wait(b);signal(b) passes a token along the waiting processes; it gates entry but does not keep b held during Q. A process may enter Q and another may immediately enter too, so no mutual-exclusion or two-process bound follows. P is outside both waits, so every process can be in P simultaneously. This is a one-use barrier, not a reusable barrier because count is never reset.
Derivation and answer
Semaphore a serializes count increments after each process finishes P. Semaphore b starts 0 and is signaled for the first time only when count=n, so no process can pass wait(b) before all have finished P. Each passing process signals b to release the next waiter. The signal occurs before Q, so Q is not mutually excluded or limited to two entrants. Thus this is a barrier, A.
Shared D starts at 100. Concurrent processes perform P1: D=D+20; P2: D=D−50; P3: D=D+10 on a time-shared uniprocessor. If X and Y are the minimum and maximum possible final values, find Y−X. Use the intended model in which each assignment's read and write can be interleaved with other processes.
Answer & solution
Official answer: 80
Method: split each assignment into a read, local arithmetic, and write; an interrupted process may later overwrite a newer shared value using its earlier read.
1. To attain the minimum, let P2 read 100 and compute 50 but delay its write. Let P1 and P3 complete their increments, then let P2 write its stored 50 last. The final result is 50, because the earlier increments are overwritten. 2. To attain the maximum, let P1 and P2 both read 100. P2 writes 50 first; P1 then writes its stored 120, overwriting the decrement. P3 reads 120 and writes 130. The final result is 130. 3. These are also bounds. Trace the final write back through the value read by its writer, and recursively through preceding writes. This dependency chain starts at 100 and can include each process's change at most once. Its smallest possible sum includes −50 but no positive changes, giving 50; its largest includes +20 and +10 but not −50, giving 130. 4. Both bounds are attainable by steps 1 and 2, so X=50 and Y=130. Their difference is 130−50=80.
Result: 80. If whole assignments were atomic, every order would instead end at 80; the intended model permits preemption within an assignment. Under that different atomic model X=Y=80 and Y−X would be zero. A uniprocessor prevents simultaneous instruction execution but does not by itself make a multi-instruction update atomic.
A size-N buffer uses empty=0, full=N, mutex=1. Here empty counts readable items and full writable slots. Producer executes wait(P),wait(mutex),add,signal(mutex),signal(Q); consumer wait(R),wait(mutex),remove,signal(mutex),signal(S). Choose A full/full/empty/empty; B empty/empty/full/full; C full/empty/empty/full; D empty/full/full/empty.
Your answer
Answer & solution
Official answer: C
Method
Follow the definitions rather than familiar variable names. Before adding an item, the producer must reserve one writable slot, so it waits on the semaphore initially N. After insertion it creates a readable item, so it signals the semaphore initially 0. The consumer performs the reverse transfer. Waiting for a resource before taking mutex also avoids holding the buffer lock while blocked for another process to make progress. Each successful pair of operations preserves the bounded-buffer accounting.
Solution
Use the definitions supplied, which reverse the usual semaphore names. full starts N and counts producer-writeable slots; empty starts 0 and counts readable items. The producer waits(full) and signals(empty); the consumer waits(empty) and signals(full), each using mutex for buffer access. Thus P=full, Q=empty, R=empty, S=full, C.
There are n processes Pi, and all t[i] initially equal 0. pmax returns an integer at least as large as each argument. Each Pi repeats: c[i]=1; t[i]=pmax(t[0],...,t[n−1])+1; c[i]=0; for every j!=i {while(c[j]); while(t[j]!=0 && t[j]<=t[i]);} Critical Section; t[i]=0; Remainder Section; Which claim is true? A:At most one process is in its critical section at any time. B:Bounded waiting holds. C:Progress holds. D:Deadlock cannot occur. Analyze the usual atomic-read/write, sequentially consistent, nonoverflowing-ticket model with initially clear choosing flags c.
Your answer
Answer & solution
Official answer: A
This is bakery-style ticket selection without a process-ID tie-breaker. The choosing flags ensure another process waits until ticket selection finishes. Under the usual atomic-read/write, sequentially consistent, nonoverflowing-ticket model, two active contenders cannot both pass each other: a smaller nonzero ticket blocks the larger, while equal tickets block both. Thus mutual exclusion holds. Two simultaneous selections can read the same old maximum and choose equal tickets; each then waits for the other forever, so progress, deadlock-freedom and eventual bounded waiting are not guaranteed. Only A. Choosing flags are understood initially clear.
For a concrete deadlock execution with two processes, both evaluate the old maximum 0 before either publishes its ticket, and both choose 1. After their choosing flags clear, each sees the other's nonzero equal ticket and waits because 1≤1. Neither reaches the code that resets its ticket to 0. A process-ID tie-breaker, as in the standard bakery algorithm, would order equal tickets; it is absent here. This shows why mutual exclusion can hold while progress and bounded waiting fail.
Two processes share turn=0. Process 0 entry waits while turn==1, then executes its critical section and sets turn=1 on exit. Process 1 waits while turn==0, executes its critical section and sets turn=0 on exit. A correct solution; B violates mutual exclusion; C violates progress; D violates bounded waiting.
Your answer
Answer & solution
Official answer: C
This is strict alternation. If process 0 finishes its critical section and remains in its remainder section, turn becomes 1. Process1 may enter and leave, setting turn back 0. A further request by process 1 is then blocked even though process 0 is not competing. This violates progress. Mutual exclusion holds because turn cannot be both 0 and 1; the intended answer is C under the standard synchronization-property definitions.
An even simpler progress witness occurs initially: only process 1 requests entry while process 0 stays forever in its remainder section. turn remains 0, so the empty critical section is inaccessible to the sole interested process. Strict alternation limits overtaking but lets an uninterested process prevent entry, which is why mutual exclusion alone is insufficient.
A nonnegative counting semaphore S uses P to decrement when permitted and V to increment. Twenty P and twelve V operations are issued in some order. Find the greatest initial S for which at least one P remains blocked after the V operations are processed.
Answer & solution
Official answer: 7.0 : 7.0
Our answer: 7
After all 12 V operations have taken effect, the total number of permits available to satisfy the 20 P operations is S0+12. At least one remains blocked exactly when S0+12<20, giving the largest integer S0=7. This concerns operations remaining blocked after all issued V operations are processed, not a temporary block earlier in some ordering.
At S0=7 there are only 19 permits over the entire execution, so twenty P operations cannot all finish. At S0=8 there are twenty permits, enough eventually to release every issued P once all twelve V operations occur. A transient empty semaphore does not prove an operation will remain blocked after future signals.
Shared B starts at 2. Concurrent P1 executes C=B−1; B=2*C. Concurrent P2 executes D=2*B; B=D−1. How many distinct final values can B have? Treat each assignment as atomic.
Answer & solution
Official answer: 3
Name P1's statements a,b and P2's c,d. The six order-preserving interleavings abcd,acbd,acdb,cabd,cadb,cdab end with B values 3,3,2,3,2,4 respectively. C and D retain the values calculated when their own reads occurred; later writes to B do not recompute them. Thus the distinct set is {2,3,4}. This is the exam's interleaving model, not an assertion that unsynchronized shared-variable C code has defined behavior.
Solution: Respecting each process’s assignment order, the possible final values of B are 2, 3, 4. Running P1 then P2 gives 3; P2 then P1 gives 4; reading both old B values before either write and leaving P1’s write last gives 2. Enumerating the six order-preserving interleavings adds no others. Thus three distinct values, with atomic statements and sequential consistency.
Processes X and Y use shared Boolean flags varP and varQ, both initially false. Their synchronization pseudocode is: X: while(true) { varP=true; while(varQ==true) { /* critical section X */ varP=false; } } Y: while(true) { varQ=true; while(varP==true) { /* critical section Y */ varQ=false; } } The critical sections are inside the inner while bodies, not after empty waiting loops. Which claim holds under the usual atomic-flag model? (A) prevents deadlock but fails mutual exclusion; (B) guarantees mutual exclusion but fails to prevent deadlock; (C) guarantees both; (D) guarantees neither.
Your answer
Answer & solution
Official answer: A
Our answer: A under atomic shared-flag model
1. If both flags become true before either loop test, both processes can enter their critical sections, so mutual exclusion fails.
2. The inner loops are not waiting loops: their bodies execute the critical section when the other flag is true. Under fair execution and terminating critical sections, a false test returns to the outer loop and reasserts the flag; there is no state where both wait permanently for an action the other cannot perform. Thus A. Literal unsynchronized C threads would instead require a memory-model analysis; the source is treated as synchronization pseudocode.
Producer-consumer pseudocode starts with semaphores n=0, s=1. Producer repeats produce(); wait(s); addToBuffer(); signal(s); signal(n). Consumer repeats wait(s); wait(n); removeFromBuffer(); signal(s); consume(). Which is true? A Producer can add but consumer can never consume. B Consumer removes at most one item. C Deadlock occurs if consumer acquires s when the buffer is empty. D n must start at 1 rather than 0 for deadlock-free operation.
Your answer
Answer & solution
Official answer: C
1. Set up the reasoning. Interpret s as the mutex and n as the number of available items. Trace the particular interleaving where the consumer runs first and locks the empty buffer.
2. Derive the result. If the consumer acquires s while n=0, it blocks on n while retaining s. The producer needs s before adding an item and signaling n, so neither can proceed. That is the deadlock in C. Correct ordering is to wait for n before acquiring the buffer mutex; inventing an initial item by setting n=1 is not a valid repair.
3. Check the interpretation. The consumer holds the very lock the producer requires to make n positive. The proper repair is to wait on n before locking s, not to pretend that an item exists by setting n=1.
Shared x starts 0. W and X each read x, add1 locally, then store; Y and Z each read x, subtract 2 locally, then store. Each process waits on a counting semaphore initially 2 before reading and signals after storing. Each executes once. Maximum final x: A−2, B−1, C1, D2.
Your answer
Answer & solution
Official answer: D
Each increment operation adds 1 to a previously read value, while each decrement subtracts 2. A causal chain of reads and writes contains at most the two increment operations, so no value can exceed 2 starting from 0. This is attainable with semaphore capacity 2: W reads 0 and pauses; Y reads 0 and writes−2; Z reads−2 and writes−4; W then writes 1; X reads 1 and writes 2. The capacity restriction is respected throughout. Thus the largest final value is 2, D.
A write stores a locally computed value based on an earlier read, so updates need not add algebraically to−2. With capacity 2, W can occupy one slot while reading 0; the other slot is reused by Y then Z, producing−2 then−4. W’s delayed write overwrites these with 1. After W leaves, X can read 1 and write 2. For the upper bound, trace a written value backward through the reads it depends on. Each increment process can appear at most once in such a causal chain, so no chain adds more than 2; decrements only decrease it. This proves both attainability and optimality.
Producer X computes a[i]=f(i), then ExitX; consumer Y calls EntryY, then computes b[i]=g(a[i]), for i=0,…, n−1. Binary semaphores R, S initially 0. Which implementation synchronizes them? A Exit=P(R), V(S);Entry=P(S), V(R). B Exit=V(R), V(S);Entry=P(R), P(S). C Exit=P(S), V(R);Entry=V(S), P(R). D Exit=V(R), P(S);Entry=V(S), P(R).
Your answer
Answer & solution
Official answer: C
In C, the consumer first signals S to indicate readiness, then waits on R; the producer waits on S before signaling R after its item has been computed. The consumer reads the item only after that R handshake. Since the next S is not issued until the preceding consumer iteration finishes, signals cannot outrun the corresponding item and collapse in a binary semaphore. A deadlocks immediately because both sides initially wait on zero semaphores. B lacks a readiness handshake, so multiple signals can collapse. In D, the producer can signal R for the next item before the consumer consumes the preceding R, again collapsing signals. Thus C provides the required synchronization.
A binary semaphore stores only whether a signal is pending, not an unbounded count. The consumer’s V(S) in C grants permission for one producer notification, then its P(R) waits for the corresponding completed a[i]. The producer cannot notify the next item without another S grant, which the consumer issues only in its next iteration. This prevents two notifications collapsing into one. In D, after the first readiness signal the producer can release R twice before the consumer takes R even once, losing a notification and potentially blocking a later consumer iteration.
Fetch_And_Add(X,i) is an atomic Read-Modify-Write instruction that reads the value of memory location X, increments it by the value i, and returns the old value of X. It is used in the pseudocode shown below to implement a busy-wait lock. L is an unsigned integer shared variable initialized to 0. The value of 0 corresponds to lock being available, while any non-zero value corresponds to the lock being not available.
AcquireLock(L){ while (Fetch_And_Add(L,1)) L = 1; }
ReleaseLock(L){ L = 0; }
This implementation (A) fails as L can overflow (B) fails as L can take on a non-zero value when the lock is actually available (C) works correctly but may starve some processes (D) works correctly without starvation
Your answer
Answer & solution
Official answer: B
Suppose one process holds the lock with L=1. A waiter executes Fetch_And_Add, obtains old value 1 and changes L to 2, so it must execute the loop body. Before that body executes, the owner releases the lock by storing L=0. The waiter then executes its pending L=1 assignment, restoring a nonzero value even though nobody holds the lock. Subsequent tests keep failing and there need be no owner left to release it. Thus B identifies a failure even without arithmetic overflow.
Check: Atomicity protects the fetch-and-add operation itself, not the following plain assignment. The interleaving is: waiter atomically changes 1→2; owner changes 2→0; waiter changes 0→1. The last store overwrites the release and leaves no holder responsible for another release.
Processes P1 and P2 use shared Boolean variables S1,S2 whose initial values are assigned randomly. Whenever they need their critical sections they execute: P1: while (S1==S2); critical section; S1=S2; P2: while (S1!=S2); critical section; S2=not(S1); Which properties are achieved? Options: (A) Mutual exclusion but not progress; (B) Progress but not mutual exclusion; (C) Neither mutual exclusion nor progress; (D) Both mutual exclusion and progress.
Your answer
Answer & solution
Answer: A (no official key was published)
P1 passes its guard only when S1≠S2; P2 passes only when S1=S2. Neither changes the shared state until leaving its critical section, so while one is inside the other’s guard stays blocking: mutual exclusion holds. Progress fails: if S1=S2 and only P1 wants to enter, P1 spins forever unless P2 participates and changes S2. The symmetric case also occurs. This is strict alternation, so A, assuming atomic sequentially consistent accesses as the pseudocode model does.
After P1 exits it sets S1=S2, making P2 eligible and itself ineligible; after P2 exits it makes S2 the opposite of S1, restoring P1’s turn. Consequently the processes alternate even if one no longer wants the critical section. Mutual exclusion is a safety property; progress additionally requires that an uninterested process not prevent an interested one from entering.
Three concurrent processes use binary semaphores initially S0=1,S1=0,S2=0: P0: while(true) { wait(S0); print '0'; release(S1); release(S2); } P1: wait(S1); release(S0); P2: wait(S2); release(S0); How many times will P0 print '0'? Options: (A) At least twice; (B) Exactly twice; (C) Exactly thrice; (D) Exactly once.
Your answer
Answer & solution
Answer: A (no official key was published)
P0 consumes the initial S0 permit and prints once, then enables P1 and P2. Each of those processes releases S0 exactly once. If both releases occur before P0 next waits on S0, binary saturation coalesces them into one permit, allowing only one further print: total 2. If P0 consumes the first released permit before the other process releases S0, it receives two separate permits and prints three times total. Thus 2 or 3 prints are possible, so the only correct choice is A, at least twice. This assumes ordinary progress/eventual scheduling; an adversarial scheduler that permanently starves runnable processes defeats any eventual-print guarantee. A counting semaphore would instead give exactly three.
The distinction between binary and counting semaphores changes the answer. A binary semaphore stores at most one available permit; release on an already available semaphore does not accumulate a second permit. P1 and P2 have no loops, so they cannot supply unbounded future permits even though P0 keeps releasing S1 and S2. That bounds the total prints above by three.
Shared lock X starts 0. enter_CS spins while atomic test-and-set(X) returns true; leave_CS writes X=0. Assess I deadlock-free; II starvation-free; III FIFO entry; IV multiple simultaneous entrants. A I only; B I/II; C II/III; D IV only.
Your answer
Answer & solution
Answer: A (no official key was published)
Atomic test-and-set allows exactly one contender to observe 0 and enter, preserving mutual exclusion. When the current holder eventually leaves and resets X, some contender can acquire it, so the lock is deadlock-free under ordinary progress assumptions. There is no FIFO order or bounded-wait guarantee: the same process can repeatedly win and starve another. Only I holds, A. X denotes shared lock storage in this pseudocode, not an ordinary pass-by-value C local.
The atomic operation returns the old flag and sets it to 1 as one indivisible action. Only one contender can see old 0, so IV is false. Once the holder releases, some waiting process can succeed, assuming the holder and scheduler make ordinary progress; this supplies deadlock freedom. But no queue orders contenders. A newly arriving or repeatedly scheduled process can keep winning before another waiter, defeating both FIFO and starvation freedom. Therefore only I is justified.
Counting-semaphore operations are P(s): decrement s and wait if s<0; V(s): increment s and wake one waiter if s≤0. Given binary-semaphore wait/signal Pb,Vb, consider: P(s): Pb(xb); s=s−1; if(s<0){Vb(xb); Pb(yb);} else Vb(xb); V(s): Pb(xb); s=s+1; if(s≤0) Vb(yb); Vb(xb); What initial values should xb,yb have respectively?
(A) 0,0 (B) 0,1 (C) 1,0 (D) 1,1
Your answer
Answer & solution
Answer: C (no official key was published)
1. The semaphore xb protects the shared count and must start unlocked at 1. The semaphore yb represents the waiting gate and must start at 0, so a P operation with negative count blocks. 2. Thus the required initial values are (1,0), option C. This answers the initialization question, not a proof of the whole implementation. 3. Under ordinary saturating binary-semaphore semantics the shown implementation can lose a wakeup: two P callers decrement to -2 and pause before Pb(yb); two V callers then both signal yb before either waiter consumes it, leaving only one stored signal. A robust implementation needs additional synchronization or a specified wakeup protocol.
Two intent flags give mutual exclusion but may deadlock
Synchronization & Concurrency
Tap to enlarge
Shared flags wants1,wants2 are initially false. P1 executes: while(true) { wants1=true; while(wants2==true); /* critical section */ wants1=false; } P2 executes: while(true) { wants2=true; while(wants1==true); /* critical section */ wants2=false; } The source places each remainder-section comment after its loop. Under atomic sequentially consistent flag operations, which statement is intended? Options: (A) Mutual exclusion is not ensured (B) Bounded waiting is not ensured (C) Critical sections must alternate strictly (D) Deadlock is not prevented, but mutual exclusion is ensured
Your answer
Answer & solution
Answer: D (no official key was published)
1. Approach. Test safety and progress separately. Two critical sections cannot overlap because each entrant advertises its intent. But if both advertise before either tests, neither can reach the instruction clearing its flag.
2. Derivation and interpretation. Under the standard sequentially consistent, atomic-read/write pseudocode model, each process sets its own wants flag before testing the other's flag and keeps it true throughout its critical section. Thus both cannot pass their tests and overlap in the critical section: whichever passes first prevents the other entering until it clears its flag. However, if both set their flags before either tests the other, each spins forever, giving deadlock. Thus D describes the decisive combination: mutual exclusion holds but deadlock prevention fails. Strict alternation is not required; one process can repeatedly enter while the other does not request entry. Option B needs care: under a broad interpretation that bounded waiting guarantees eventual entry, deadlock also violates it. In the usual bounded-overtaking formulation, distinguish this progress failure from another process overtaking a waiter indefinitely; the latter cannot occur here. D is the intended most specific answer, while the phrasing of B can be read more broadly.
Atomic fetch-and-set(x,y) sets shared location x to 1 and returns its old value in y, without an intervening access. Binary semaphore code is: P(S): do { fetch-and-set(S.value,y); } while(y); V(S): S.value=0; Which statement is true? Options: (A) P may fail to work if context switching is disabled inside it (B) A normal load/store pair can replace atomic fetch-and-set (C) V is incorrectly implemented (D) The code does not implement a binary semaphore
Your answer
Answer & solution
Answer: A (no official key was published)
1. P repeatedly atomically exchanges S.value with 1 and succeeds only when the previous value was 0. V releases it by storing 0.
2. On a uniprocessor, a process spinning in P with context switching disabled can prevent the lock owner from running V, so progress can fail. Separate load/store instructions are not atomic and allow two contenders to enter.
3. Thus A is true. This is a busy-wait semaphore using 0 for available and 1 for held; assume the intended atomic shared-memory model.
4. Teaching check: Atomicity prevents two contenders from both observing an available semaphore and entering. It does not guarantee progress if the spinning contender prevents the holder from being scheduled. Thus mutual-exclusion correctness and scheduling/liveness assumptions must be considered separately.
Three processes repeatedly synchronize at a barrier. Shared process_arrived and process_left start at 0. S is a binary semaphore, initially available; P acquires and V releases it. Each process calls: void barrier(void) { 1: P(S); 2: process_arrived++; 3: V(S); 4: while (process_arrived != 3); 5: P(S); 6: process_left++; 7: if (process_left == 3) { 8: process_arrived=0; 9: process_left=0; 10: } 11: V(S); } Use the intended shared-memory pseudocode model, not a claim of data-race-safe modern C. Why is the implementation incorrect? Options: (A) The use of binary semaphore S makes it wrong (B) Two consecutive barrier invocations can deadlock (C) Lines 6–10 do not need a critical section (D) It is correct with two processes instead of three
Your answer
Answer & solution
Answer: B (no official key was published)
1. Once all three arrive, process_arrived=3. Let P leave the first barrier, increment process_left to 1, and immediately enter its next barrier before Q and R have finished the first.
2. It increments process_arrived to 4. If Q and R have not passed the first barrier’s while test, they now wait for process_arrived==3, and P also waits in its second invocation.
3. No one can perform the final reset: deadlock. Binary semaphores correctly protect the updates and are not the cause; the missing separation between barrier generations is.
4. The same issue can occur with two processes. Hence B.
5. Teaching check: The first invocation opens when arrival count reaches three, but the code does not close entry to the next generation. An early returning process can raise the count to four while another still tests for equality with three. A protected increment alone does not prevent mixing generations.
Three processes repeatedly synchronize at a barrier. Shared process_arrived and process_left start at 0. S is a binary semaphore, initially available; P acquires and V releases it. Each process calls: void barrier(void) { 1: P(S); 2: process_arrived++; 3: V(S); 4: while (process_arrived != 3); 5: P(S); 6: process_left++; 7: if (process_left == 3) { 8: process_arrived=0; 9: process_left=0; 10: } 11: V(S); } Use the intended shared-memory pseudocode model, not a claim of data-race-safe modern C. Which proposed repair addresses its reuse problem? The phrase “first process” in B is only a conceptual generation gate and needs a concrete synchronization implementation. Options: (A) Replace lines 6–10 by process_arrived-- (B) At barrier entry, the first process waits for process_arrived to become zero before executing P(S) (C) Disable context switching throughout the barrier (D) Make process_left private instead of shared
Your answer
Answer & solution
Answer: B, with generation-entry qualification (no official key was published)
1. The intended repair is to prevent a process from incrementing the next generation’s arrival count until the previous generation has reset process_arrived to zero, corresponding to B. It must wait before acquiring S, leaving S available to the final departing process that performs the reset.
2. A lets an early departure lower process_arrived while others still need to observe 3; C prevents necessary scheduling on a uniprocessor; D prevents the shared departure count reaching 3. However the phrase first process to enter is a conceptual generation gate, not complete executable synchronization.
3. Merely adding an unconditional while(process_arrived!=0) to every invocation blocks the second arrival of the same generation; waiting only one vaguely designated process while allowing another new-generation entrant through is also insufficient. A concrete reusable barrier needs a correctly synchronized generation flag or two-turnstile design.
4. Teaching check: Waiting while holding S would prevent the final departing process from acquiring S to reset the counters. Waiting must therefore occur outside that critical section, and it must distinguish generations correctly. A two-turnstile or generation-counter barrier is a concrete way to enforce this separation.
Two concurrent processes use binary semaphores S,T. Process P loops forever: W: [synchronization]; print '0'; print '0'; X: [synchronization]. Process Q loops forever: Y: [synchronization]; print '1'; print '1'; Z: [synchronization]. Synchronization can be placed only at W,X,Y,Z. P(S) means wait/decrement and V(S) means signal. Which always gives an output starting 001100110011...? A. W=P(S), X=V(S), Y=P(T), Z=V(T); S=T=1 initially B. W=P(S), X=V(T), Y=P(T), Z=V(S); S=1,T=0 initially C. W=P(S), X=V(T), Y=P(T), Z=V(S); S=T=1 initially D. W=P(S), X=V(S), Y=P(T), Z=V(T); S=1,T=0 initially
Your answer
Answer & solution
Answer: B (no official key was published)
1. The required output demands both pairwise exclusion and alternation starting with P's zeros. Initially only P should have permission: S=1 and T=0. 2. P passes wait(S), prints both zeros, then signals T. Q cannot print any one until this signal; once released it consumes T, prints both ones and signals S. 3. P's next wait(S) cannot pass before Q completes its pair. Inductively the execution consists of 00,11,00,11,..., so B works. 4. In A independent locks allow arbitrary interleaving. C initially lets both processes enter, so even the first pair need not be 00. In D Q waits forever on T because no other process signals T.
Solution: Initially give P permission to run by setting S=1 and block Q with T=0. P waits on S at W, prints both zeroes, and signals T at X. Q waits on T at Y, prints both ones, and signals S at Z. Each process therefore hands permission to the other only after completing its pair, forcing 00,11,00,11,… starting with 00. This is B. Separate locks do not coordinate the processes, and initializing both cross-signalling semaphores to one would permit initial interleaving.
Two concurrent processes use binary semaphores S,T. Process P loops forever: W: [synchronization]; print '0'; print '0'; X: [synchronization]. Process Q loops forever: Y: [synchronization]; print '1'; print '1'; Z: [synchronization]. Synchronization can be placed only at W,X,Y,Z. P(S) means wait/decrement and V(S) means signal. Which ensures the output never contains 0 1^n 0 or 1 0^n 1 with n odd? A. W=P(S), X=V(S), Y=P(T), Z=V(T); S=T=1 B. W=P(S), X=V(T), Y=P(T), Z=V(S); S=T=1 C. W=P(S), X=V(S), Y=P(S), Z=V(S); S=1 D. W=V(S), X=V(T), Y=P(S), Z=P(T); S=T=1
Your answer
Answer & solution
Answer: C (no official key was published)
1. The forbidden patterns mean a run of ones between zeros, or zeros between ones, must have even length. It is sufficient for each process to print its identical pair atomically. 2. C uses the same initially available semaphore at both W and Y. Only one process can enter its two-print critical section, and it releases the mutex only after the pair. 3. Output is thus a concatenation of whole 00 and 11 blocks. Adjacent blocks of the same digit may merge, but their lengths remain multiples of two, proving the desired property. 4. A and B initially allow both processes inside, permitting P's first 0, Q's first 1, P's second 0: a forbidden 010. D does not make P acquire a common mutex and likewise does not ensure whole-pair exclusion. Therefore C.
Solution: Use one common binary semaphore S, initially one, as a mutex around both print statements of either process: wait(S) at W and Y, signal(S) at X and Z. Each critical section then emits either 00 or 11 without interleaving, so any run between opposite digits is a concatenation of equal pairs and has even length. That is C. For example, when independent locks or two initially available cross-signalling permissions let P emit its first zero, Q one one, and P its second zero, the forbidden substring 010 occurs. Mutual exclusion of entire pairs is the needed property, not merely exclusion within each individual process.
Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(i): Fill the while condition in enter_cs(){while(blank);} and the statement in leave_cs(){blank;} using this instruction.
Answer & solution
Answer: enter_cs: while (TEST_AND_SET(&mutex)) { } ; leave_cs: mutex=0; (no official key was published)
Use the shared lock variable mutex, initially zero: void enter_cs(void) { while (TEST_AND_SET(&mutex)) { } } void leave_cs(void) { mutex = 0; } TEST_AND_SET atomically returns the old value and writes one. Exactly one contender observing the unlocked zero receives zero and leaves the loop; later contenders receive one and keep spinning. Releasing the lock restores zero for a future acquisition. This is pseudocode for the given atomic primitive and a shared lock, not a claim that an ordinary non-atomic C integer and a handwritten function implement modern concurrent-C synchronization. The source's hyphenated function names are rendered with underscores to make the names valid C identifiers.
Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(ii): For the resulting spinlock entry/exit solution, determine whether it is deadlock-free and starvation-free.
Answer & solution
Answer: Deadlock-free under the usual progress assumptions; not starvation-free. (no official key was published)
With atomic TEST_AND_SET, one contender acquires any free lock, and a holder that finishes its finite critical section releases the lock. Under the usual assumptions that a holder continues to receive execution time and eventually exits, the lock is deadlock-free: processes do not remain mutually blocked with no one able to proceed. It is not starvation-free, since a waiting process is not assigned a turn. Each time the lock is released another contender can acquire it first, so one process can lose indefinitely even while other processes keep making progress. As with any spinlock, a scheduler that prevents the holder from running can itself defeat progress; deadlock-freedom is not an unconditional scheduling guarantee.
Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(iii): If the three TEST_AND_SET steps were not atomic, give an interleaving violating mutual exclusion.
Answer & solution
Answer: Both processes can read mutex=0 before either sets it, so both enter. (no official key was published)
Initially mutex=0. Split TEST_AND_SET into the source steps A1: y=*x; A2: *x=1; A3: return y. Interleave two processes as follows: 1. P executes A1 and stores local yP=0. 2. Q executes A1 and stores local yQ=0. 3. P executes A2, writing mutex=1. 4. Q executes A2, also writing mutex=1. 5. P executes A3 and returns its saved zero; its while condition is false and it enters the critical section. 6. Q executes A3 and returns its saved zero; it also enters before P leaves. The final shared value one does not distinguish the two prior reads. Atomicity must cover the read and write as one indivisible operation.
Circular buffer size 100, indices first=last=0, semaphores b_full=0,b_empty=100. Producer repeats produce item; p1 blank; put into buf[first]; first=(first+1)%100; p2 blank. Consumer repeats c1 blank; take from buf[last]; last=(last+1)%100; c2 blank; consume item. Original20(a): Fill p1,p2,c1,c2 for one producer and one consumer.
Answer & solution
Answer: p1: wait(b_empty); p2: signal(b_full); c1: wait(b_full); c2: signal(b_empty). (no official key was published)
Complete the source placeholders with: p1: wait(b_empty); p2: signal(b_full); c1: wait(b_full); c2: signal(b_empty); The producer reserves an empty slot before writing buf[first] and advancing first, then announces a full slot. The consumer reserves a full slot before reading buf[last] and advancing last, then announces an empty slot. With b_empty initially BUFSIZE=100 and b_full initially zero, counting semaphores prevent overrun and underrun. Only one producer updates first and only one consumer updates last, so no additional mutex is needed for this single-producer/single-consumer algorithm under the usual atomic semaphore and memory-visibility assumptions. A semaphore count can exclude a reserved slot temporarily while its operation is in progress; b_empty+b_full need not equal BUFSIZE at every instruction boundary.
Mutex additions for multiple producers and consumers
Synchronization & Concurrency
Tap to enlarge
Circular buffer size 100, indices first=last=0, semaphores b_full=0,b_empty=100. Producer repeats produce item; p1 blank; put into buf[first]; first=(first+1)%100; p2 blank. Consumer repeats c1 blank; take from buf[last]; last=(last+1)%100; c2 blank; consume item. Original20(b): Introduce one additional semaphore and one statement at each location: immediately after p1, before p2, after c1, before c2 so the program supports multiple producers/consumers.
Answer & solution
Answer: Initialize semaphore mutex=1; after p1 and c1 insert wait(mutex); before p2 and c2 insert signal(mutex). (no official key was published)
Add a binary semaphore mutex initialized to one. Insert wait(mutex) immediately after p1 and immediately after c1, and signal(mutex) immediately before p2 and immediately before c2. The resulting operation order is: Producer: wait(b_empty); wait(mutex); write buf[first]; advance first; signal(mutex); signal(b_full). Consumer: wait(b_full); wait(mutex); read buf[last]; advance last; signal(mutex); signal(b_empty). This serializes updates to the shared buffer and indices across all producers and consumers. Slot availability is awaited before taking the mutex. Reversing that order can deadlock, for example a consumer holding the mutex while waiting for an item prevents a producer from inserting one. Producing and consuming the actual item stay outside the mutex-protected buffer operations.
In Peterson’s entry code for process i: set flag[i]=true; turn=j; while(P) wait; enter critical section; then clear flag[i]. Choose P: flag[j] AND turn=i; flag[j] AND turn=j; flag[i] AND turn=j; flag[i] AND turn=i. Distinguish progress from safety alone.
Your answer
Answer & solution
Answer: B for Peterson mutual exclusion with progress (no official key was published)
Step 1: Process i announces intent with flag[i]=true and sets turn=j, yielding priority to j. It should wait only while j also wants entry and j has priority: flag[j] AND turn=j, option B.
Step 2: If both flags are true, the last write to turn selects one waiting process and lets the other enter. If j leaves, it clears flag[j], immediately releasing i’s wait regardless of turn. Atomic reads/writes and sequentially consistent ordering are assumed.
Qualification: The literal question mentions only mutual exclusion. Option C, testing its own flag with turn=j, can preserve exclusion while blocking a lone entrant forever. It is not Peterson’s correct solution because progress fails. B is the predicate satisfying the intended full critical-section requirements.
GFG variant: P1 executes S1 wait until R1 free; S2 set R1 busy; S3 wait until R2 free; S4 set R2 busy; S5 use both; S6 free R1; S7 free R2. P2 executes Q1 wait until R2 free; Q2 set R2 busy; Q3 wait until R1 free; Q4 set R1 busy; Q5 use both; Q6 free R2; Q7 free R1. Initially both free. Each test and subsequent set is a separate operation.
Answer & solution
Answer: Yes: with one-shot execution and atomic reads and writes, the opposite acquisition order prevents overlapping use (no official key was published)
Program, assume each individual flag read or write is atomic, but test-and-set is not, and each process executes its printed sequence once. Mutual exclusion of the actual use intervals S5 and Q5 is nevertheless guaranteed. Suppose the intervals overlapped. Neither process could yet have released a resource. P2 must therefore have passed its R1 test Q3 before P1 sets R1 at S2, giving Q3<S2. Similarly P1 must pass its R2 test S3 before P2 sets R2 at Q2, giving S3<Q2. Program order imposes S2<S3 and Q2<Q3. Combining yields the impossible strict cycle S2<S3<Q2<Q3<S2. Hence an overlapping execution is impossible. Separate tests and sets alone are not enough to prove a race in this particular opposite-order program.
The only possible intervening freeing operation is P1’s S6, which follows completion of S5. Therefore P2 cannot reach Q5 before P1 finishes its use. This is poor progress behavior, not an overlapping-use counterexample. These conclusions concern the printed one-shot programs; an unspecified outer repetition loop or non-atomic/memory-reordered implementation is a different model.
GFG variant: P1 executes S1 wait until R1 free; S2 set R1 busy; S3 wait until R2 free; S4 set R2 busy; S5 use both; S6 free R1; S7 free R2. P2 executes Q1 wait until R2 free; Q2 set R2 busy; Q3 wait until R1 free; Q4 set R1 busy; Q5 use both; Q6 free R2; Q7 free R1. Initially both free. Each test and subsequent set is a separate operation. Exchange Q1 with Q3 and Q2 with Q4.
Answer & solution
Answer: Mutual exclusion fails after reordering, but there is no resource deadlock (no official key was published)
After swapping the the paper operations, both processes check/set R1 and then check/set R2. Name the new P2 order Q1′=test R1, Q2′=set R1, Q3′=test R2, Q4′=set R2, followed by use and the original releases. A violating interleaving is S1,Q1′,S2,Q2′,S3,Q3′,S4,Q4′, followed by overlapping S5 and Q5. Both tests of each free flag precede either write to that flag, so both reach their use intervals. This shows why a real atomic lock operation is required.
There is no resource deadlock in the reordered the paper protocol: a process waiting on R2 has already passed the R1 test. Any competing process that made R2 busy has also passed both tests and can finish and release; it cannot be waiting to acquire R1 afterward. This excludes a circular resource wait, assuming a runnable process eventually runs. It does not promise fairness or fix mutual exclusion.
Its one-shot nonoverlap and self-wait deadlock from parts (a),(b) remain.
R=W=0, binary semaphore mutex=1. Reader acquires mutex, and if W==0 increments R then executes box 1; otherwise executes box 2 and retries. After reading it acquires mutex, decrements R and releases mutex. Writer acquires mutex; if box 3 is true it releases mutex and retries; otherwise it sets W=1, releases mutex, writes, then acquires mutex, sets W=0 and releases mutex. Fill boxes 1,2,3.
Answer & solution
Answer: (1) signal(mutex); (2) signal(mutex); (3) R>0 || W!=0. (no official key was published)
The complete intended protocol is:
Reader() {
L1: wait(mutex);
if (W == 0) {
R = R + 1;
signal(mutex); // box 1
} else {
signal(mutex); // box 2
goto L1;
}
/* read shared data */
wait(mutex);
R = R - 1;
signal(mutex);
}
Writer() {
L2: wait(mutex);
if (R > 0 || W != 0) { // box 3
signal(mutex);
goto L2;
}
W = 1;
signal(mutex);
/* write shared data */
wait(mutex);
W = 0;
signal(mutex);
}
wait/signal must implement a genuine atomic binary semaphore with appropriate memory visibility. Merely reading and writing an ordinary flag is not a substitute. All tests and updates of R,W occur under mutex, so checking admission and registering the admitted reader/writer are atomic relative to competitors. A writer enters only when no reader and no writer is active, and W=1 prevents later admissions until it finishes. Multiple readers are allowed while W=0. Both reader branches must release mutex; retaining it would block exits or retries and can deadlock. The mutex protects admission bookkeeping, not the whole read/write operation; R and W reserve access while mutex is released. Safety holds, but fairness is not guaranteed.
R=W=0, binary semaphore mutex=1. Reader acquires mutex, and if W==0 increments R then executes box 1; otherwise executes box 2 and retries. After reading it acquires mutex, decrements R and releases mutex. Writer acquires mutex; if box 3 is true it releases mutex and retries; otherwise it sets W=1, releases mutex, writes, then acquires mutex, sets W=0 and releases mutex. With correct boxes, can writers starve?
Answer & solution
Answer: Yes. Waiting writers do not prevent new readers from entering. (no official key was published)
Consider two streams of readers whose reading intervals overlap. Before the last current reader exits, a new reader acquires mutex, observes W=0, increments R and begins reading. Arrange this repeatedly so R never becomes 0. A waiting writer may acquire mutex infinitely often, but each time it finds R>0, releases mutex and retries. It therefore never reaches W=1, even though every individual read finishes. A pending writer is not recorded anywhere: W means an active writer, not a waiting writer. Consequently new readers remain admissible throughout this schedule. This is starvation, not deadlock, since readers keep making progress. Even fairness in acquiring the bookkeeping semaphore would not repair this example because the writer gets turns and still cannot enter. Avoiding it requires a different admission policy, for example recording waiting writers and refusing new readers while a writer waits, together with suitable queue fairness; that change is outside the requested three boxes.
TSET register,flag atomically copies flag into register and sets flag=1. Give entry and exit pseudocode for a critical region.
Answer & solution
Answer: Spin until TSET returns 0; release by setting flag to 0. (no official key was published)
Initialize a shared flag to 0 before any competing process starts. Each process uses its own register r.
shared flag := 0
entry:
repeat
TSET r, flag
until r = 0
critical_region()
exit:
flag := 0
TSET must run on every retry; reading a stale r in a spin loop would never acquire the lock. When flag=0, exactly one atomic TSET can observe that 0 and simultaneously change flag to 1. That process enters; all later tests obtain 1 and continue waiting. Only the owner clears the flag on exit. This establishes mutual exclusion, assuming atomic release stores and the abstract sequentially consistent memory model of the question. Real machines additionally require appropriate acquire/release memory ordering. The scheme busy-waits and does not by itself guarantee bounded waiting or freedom from starvation.
A one-slot producer-consumer buffer uses count=0 initially. Tests and assignments of count are individually atomic. Producer repeats: produce item; if count=1 then sleep; put item in buffer; count:=1; wakeup(Consumer). Consumer repeats: if count=0 then sleep; remove item; count:=0; wakeup(Producer); consume item. Show an execution where both processes sleep.
Answer & solution
Answer: A wakeup between the consumer’s test and sleep is lost; producer later sleeps on the full buffer. (no official key was published)
Assume ordinary sleep/wakeup semantics: waking a process not currently asleep does not save a future wakeup token. The following interleaving is legal even though each test and assignment is atomic. 1. Consumer tests count=0 and gets true, but is preempted just before executing sleep. 2. Producer produces an item, tests count=1 (false), places the item, then atomically sets count=1. 3. Producer calls wakeup(Consumer). Consumer is not sleeping yet, so the notification is lost. 4. Consumer resumes at the pending sleep instruction and goes to sleep, without rechecking count. The buffer is full and count remains 1. 5. Producer begins its next iteration and produces another item. Its count=1 test is true, so it sleeps waiting for space. Now both processes are asleep. Only the sleeping consumer could remove the buffered item and wake the producer; only the sleeping producer could issue another consumer wakeup. Individual atomicity of test and assignment does not make the combined test-and-sleep sequence atomic. A semaphore that retains notifications, or correctly synchronized condition-variable wait with a predicate loop, prevents this lost-wakeup window.
What is a computation whose result depends on relative process speeds called: cycle stealing, race condition, time lock, deadlock?
Your answer
Answer & solution
Answer: B (no official key was published)
A race condition occurs when competing execution orders affect the result of shared operations. For example, two processes that each read, increment and write a counter may overwrite one another’s update depending on timing. Synchronization is needed when the intended result must not depend on such an interleaving. This is B. Deadlock instead means processes cannot make progress, while cycle stealing describes bus access by a device.
Similar questions1 more → · asked again: GATE 1992, Q2(x)
Net semaphore updates
Synchronization & Concurrency
Tap to enlarge
A counting semaphore starts at 10. Six completed P(wait) and four completed V(signal) operations occur. Find the final value among 0, 8, 10, 12.
Your answer
Answer & solution
Answer: B: 8 (no official key was published)
Each completed wait consumes one available unit, decreasing the count by 1. Each signal adds one unit. Thus the net change is−6+4=−2, and the final count is 10−2=8. Because all six waits are stated to complete and the initial count is sufficient even before signals, no blocking ambiguity affects this arithmetic. Hence B; counting only the signals would incorrectly increase the initial value.
Represent the graph with edges S1→S2,S1→S3,S1→S4,S1→S5,S2→S4,S4→S5,S3→S5 using parbegin/parend.
Answer & solution
Answer: S1; parbegin {S2;S4} || {S3} parend; S5. (no official key was published)
S1 must finish first. Afterward S3 can run independently of the chain S2 then S4. S5 must wait for both branches. A structured program is:
begin
S1;
parbegin
begin
S2;
S4;
end
S3;
parend;
S5;
end
Here parbegin starts its two child statements concurrently, and parend joins them. The first child is a sequential block, so S2 precedes S4. The second child is S3. The final join guarantees both S3 and S4 finish before S5. Edges S1→S4 and S1→S5 are already implied by the paths through S2/S4, but are still satisfied. There is no imposed order between S3 and S2 or between S3 and S4, so the program preserves the graph's available parallelism rather than unnecessarily serializing it.
Nine processes repeat P(mutex);critical section;V(mutex). A tenth replaces its initial P by V. What maximum number can be inside simultaneously?
Your answer
Answer & solution
Answer: D: 10, none of 1, 2, 3 (no official key was published)
The faulty process never consumes a permit when entering and adds permits both before entering and after leaving. With a counting semaphore, it can complete enough loops to accumulate at least nine permits while the others wait to run. Then schedule all nine correct processes through P and pause each inside its critical section. Finally let the faulty process enter too: all ten are inside. Ten is the absolute upper bound because only ten processes exist, so it is attained. Even a saturating binary semaphore can be repeatedly reopened by the faulty process to admit more peers before they leave. Thus D.
Three processes use a shared resource R mutually exclusively and nonpreemptively. Each has a unique fixed priority in {1,2,3}, with 3 highest. Shared state: semaphore mutex=1; semaphores proceed[1..3]=0; Boolean R_requested[1..3]=false; Boolean busy=false. Each process repeats request_R(my_priority); P(proceed[my_priority]); use R; release_R(my_priority). The supplied request_R(p) performs P(mutex); if busy then R_requested[p]:=true else begin V(proceed[p]); busy:=true end; V(mutex). Give release_R so each allocation goes to the highest-priority current requester. The shared-data declaration is printed as process[3] in the reproduction, while uses consistently say proceed; normalize that apparent naming typo explicitly.
Answer & solution
Answer: Under mutex, select the highest set request flag, clear it and signal that process while retaining busy=true; set busy=false only if no process waits. (no official key was published)
The release operation must inspect request flags and either transfer ownership or mark the resource free as one atomic critical section. Otherwise a new requester could take R between checking the flags and waking a waiting process. This code uses the same proceed array as the process and request routines; the source's isolated process spelling is treated as a declaration typo.
procedure release_R(my_priority):
P(mutex)
chosen := 0
for p := 3 downto 1 do
if R_requested[p] then
chosen := p
break
if chosen = 0 then
busy := false
else
R_requested[chosen] := false
busy := true
V(proceed[chosen])
V(mutex)
The parameter my_priority identifies the releasing owner but is not needed to select the next one. Preconditions are that only the current owner calls release_R, each process has at most one outstanding request, and P/V have standard semaphore semantics. The no-waiter branch does not signal a semaphore: the next arriving requester will signal its own proceed entry in request_R before doing P on it.
Why keep busy true during handoff? A signaled process may not run immediately. The resource is nevertheless reserved for it; setting busy false would let a newcomer receive a second grant. Clearing the chosen flag prevents a later release from treating the same already-granted request as still waiting. Lower-priority flags remain set, preserving their requests.
Since priorities are unique and the loop scans 3,2,1, it chooses the highest pending priority at the moment of allocation. A higher-priority process arriving after that atomic choice must wait: the resource is nonpreemptive, so priority does not revoke an existing grant. At most one grant exists at a time, maintaining mutual exclusion. This scheme can starve a low-priority requester if higher-priority requests keep arriving; starvation freedom was not requested and does not follow from strict priority allocation.
What distinguishes a critical section of a program?
Your answer
Answer & solution
Answer: C: access to shared resources (no official key was published)
A critical section is code that accesses shared state or a shared resource in a way requiring coordination with other concurrent executions. Uncontrolled overlap can violate an invariant, so a mutual-exclusion mechanism is typically needed. The definition does not require a semaphore specifically: locks, monitors, atomic operations or other protocols may enforce the required property. Nor is every short or computationally important block a critical section. The shared-resource access is the relevant characteristic, C.
fork L creates a new process starting at label L while the original continues. join V atomically decrements V and terminates the arriving process unless the new value is zero. For N=2; M=2; fork L3; fork L4; S1; L1: join N; S3; L2: join M; S5; goto next; L3: S2; goto L1; L4: S4; goto L2; next:, draw the precedence graph for S1..S5. The goto next after S5 is present in GFG but omitted in GateForum.
Answer & solution
Answer: Edges S1→S3, S2→S3, S3→S5, S4→S5 (no official key was published)
After the two forks there are three branches. The original executes S1, the L3 branch executes S2, and the L4 branch executes S4. There is no synchronization among those three statements, so they can occur in any order or overlap.
The S1 and S2 branches both reach join N. Because N starts at 2, the first arrival changes N to 1 and terminates; the second changes N to 0 and survives. Exactly one process therefore continues to S3, and S3 cannot start until both S1 and S2 have finished. This gives edges S1→S3 and S2→S3. The identity of the surviving process is irrelevant to the statement ordering.
The branch completing S3 and the branch completing S4 both reach join M. The same counting argument, with M initially 2, permits S5 exactly once, after both predecessors finish. Add edges S3→S5 and S4→S5. These four edges form the transitive reduction: draw S1 and S2 feeding S3, then S3 and S4 feeding S5. The additional transitive relations S1→S5 and S2→S5 need not be drawn.
This finite five-statement interpretation uses the paper's explicit goto next after S5. Its execution is not captured by the intended one-node-per-statement DAG. Omitting the jump is a material control-flow variant, not harmless punctuation.
Draw the precedence graph of nine concurrent branches (separated here by |): S1;V(a);V(b) | P(a);S2;V(c);V(d) | P(c);S4;V(e) | P(d);S5;V(f) | P(e);P(f);S7;V(k) | P(b);S3;V(g);V(h) | P(g);S6;V(i) | P(h);P(i);S8;V(j) | P(j);P(k);S9. All variables a through k are semaphores. This is the GFG version. GateForum instead has V(c) after S4 and P(j);P(j);P(k) before S9. Initial semaphore values are not explicitly supplied; state the synchronization assumption.
Answer & solution
Answer: With semaphores initially zero: 1→2, 1→3, 2→4, 2→5, 4→7, 5→7, 3→6, 3→8, 6→8, 7→9, 8→9 (no official key was published)
Assume the usual precedence convention: every semaphore initially equals zero, P waits for and consumes one signal, and V supplies one signal. Initialization is essential: positive initial tokens would allow some statements to run before their supposed predecessors. With initially-zero semaphores, map each signal after a statement to the wait before another statement.
The labeled dependency edges are S1−a→S2, S1−b→S3; S2−c→S4, S2−d→S5; S4−e→S7, S5−f→S7; S3−g→S6, S3−h→S8; S6−i→S8; S8−j→S9 and S7−k→S9. This edge list is a complete exact specification of the requested graph. To draw it, put S1 at the top, S2 and S3 below it, S4/S5 below S2, S6 below S3, S7 below S4/S5, S8 below S6, and S9 below S7/S8; include the additional direct S3→S8 edge. That direct edge is transitively redundant because S3→S6→S8 already holds, but faithfully represents semaphore h.
S7 is a join: it cannot execute until both S4 and S5 have completed. Similarly S8 waits for both signals from S3 and S6, and S9 joins the two sides. Statements on different sides need not execute in a fixed order.
Its V(c) after S4 supplies no e token, so S7 is permanently blocked at P(e). Its final branch also waits twice on j, although S8 signals j only once, so S9 blocks at its second P(j), even independently of the missing k signal. Under fair execution, S1,S2,S3,S4,S5,S6,S8 may finish; S7 and S9 do not.
Precedence versus control flow in conditional code
Synchronization & Concurrency
Tap to enlarge
The printed straight-line code is S1: read n; S2: i:=1; S3: if i>n goto next; S4: a(i):=i+1; S5: i:=i+1; S6: next: write a(i). No backward jump is printed. Draw its precedence graph, stating the treatment of conditional execution.
Answer & solution
Answer: Precedence 1→3, 2→3, 3→4, 4→5, 5→6, 3→6; statements 4 and 5 run only on the false branch (no official key was published)
The source calls for a precedence graph but contains a conditional jump, so an ordinary unguarded task DAG cannot by itself specify whether S4 and S5 execute. A faithful control-flow graph is S1→S2→S3, with S3 true→S6 and S3 false→S4→S5→S6. This edge list completely specifies the literal execution graph; there is no loop-back edge.
For potential parallel execution, S1 and S2 are independent initial tasks: the former writes n and the latter writes i. S3 needs both values, giving S1→S3 and S2→S3. On the false branch, keep S3→S4→S5→S6. S4 must precede S5 because it reads the old i both as an index and as the right-side operand; S5 changes i. S6 must see the incremented i on this branch. On the true branch, S6 follows S3 directly without executing S4 or S5. Thus a conservative guarded precedence description has edges 1→3,2→3,3→4,4→5,5→6,3→6, with 4 and 5 guarded by i≤n.
Do not conflate this graph with a pure data-dependence graph, which would omit some control edges and include direct uses of i. Also do not insert a guessed loop. With n≥1 the literal code assigns a(1), increments i to 2, then writes a(2), which it has not initialized. With n<1 it immediately writes a(1), also not initialized here. These are semantic concerns in the printed fragment, not permission to change its instructions. The question lacks enough conventions for a unique unqualified concurrency graph.
The printed straight-line code is S1: read n; S2: i:=1; S3: if i>n goto next; S4: a(i):=i+1; S5: i:=i+1; S6: next: write a(i). No backward jump is printed. Can its graph be converted into a concurrent program using parbegin–parend only?
Answer & solution
Answer: Not with parbegin–parend alone preserving the conditional skip. With an ordinary conditional as well, S1 and S2 can run in parallel, followed by S3-controlled work. (no official key was published)
A parbegin–parend block starts all of its component branches and waits for them all to finish. It expresses fork/join synchronization, not a data-dependent choice to omit a branch. In the printed program S4 and S5 must be skipped if i>n, and must execute in order otherwise. Therefore an unconditional composition using only sequential composition and parbegin–parend cannot represent the exact conditional semantics. This is the sense in which the answer is no.
If ordinary conditionals are allowed alongside parbegin–parend, a simple equivalent ordering is: parbegin read n; i:=1 parend; if i≤n then begin a(i):=i+1; i:=i+1 end; write a(i). The first two statements have disjoint write sets, so running them concurrently is safe; the join ensures both values are ready before the test. The remaining statements retain their branch and anti-dependence order. This transformation preserves even the original fragment's possible uninitialized-array access; it does not repair it.
One must distinguish this semantic issue from the graph-theoretic claim that every precedence DAG can be expressed by nested fork/join. That latter claim is false in general, but no particular non-series-parallel graph should be asserted here without specifying which dependence convention produced it. The conservative dependency ordering of part (a), once branch guards are disregarded, is structurally fork/join compatible. The actual obstacle under the literal word “only” is conditional execution. If the examiner intended a different dependence-only graph or omitted loop, that intent is not established by the paper.
Implement DAG edges S1→S2,S1→S3,S2→S4,S2→S5,S3→S5,S6→S4,S6→S5 using parbegin/parend and semaphores. Note S6 is a source, not a sink.
Answer & solution
Answer: One zero-initialized semaphore per edge; each task waits on incoming edges and signals outgoing edges. (no official key was published)
Use semaphores e12,e13,e24,e25,e35,e64,e65, each initialized to zero. P(e) waits and decrements atomically; V(e) signals. Run these six branches in one parbegin/parend block:
begin S1; V(e12); V(e13) end begin P(e12); S2; V(e24); V(e25) end begin P(e13); S3; V(e35) end begin P(e24); P(e64); S4 end begin P(e25); P(e35); P(e65); S5 end begin S6; V(e64); V(e65) end
For each edge u→v, its semaphore can be signalled only after Su finishes, and Sv cannot start until its wait succeeds. Hence every required precedence is enforced. Distinct edge semaphores prevent one successor from consuming another's notification. They also allow a signal to arrive before its matching wait without being lost.
Only S1 and S6 have no predecessors, so they can begin concurrently. S4 awaits S2 and S6, while S5 awaits S2,S3,S6. In particular, the arrows drawn upward from S6 end at S4 and S5; reversing them would implement a different graph. No extra ordering is imposed between incomparable task executions, although a blocked wait can hold a branch until all its own predecessors finish. With terminating tasks and fair scheduling this acyclic dependency system has no synchronization deadlock.
Similar questions1 more → · asked again: GATE 1998, Q1.31
Counting completed semaphore operations
Synchronization & Concurrency
Tap to enlarge
A counting semaphore starts at 7. Twenty P and fifteen V operations complete. What is its final value?
Select all that apply
Answer & solution
Answer: B: 2 (no official key was published)
Each completed P consumes one permit, decreasing the value by one; each V adds one. The net change is −20+15=−5, so the final value is 7−5=2. The word completed matters: blocked, uncompleted waits cannot simply be counted as successful acquisitions in a nonnegative semaphore convention. The stated totals permit an interleaving with enough signals before later waits, so no contradiction is implied by having twenty waits after an initial value of only seven.
Draw the precedence graph for this concurrent program. Within begin/end statements are sequential; parbegin/parend runs its components concurrently and joins them: S1; parbegin begin S2; S4 end; begin S3; parbegin S5; begin S6; S8 end parend end; S7 parend; S9
Answer & solution
Answer: Edges: 1→2,3,7; 2→4; 3→5,6; 6→8; 4,5,8,7→9. (no official key was published)
S1 executes before the outer fork. Its three branches start with S2, S3, and S7. In the first branch S2 precedes S4. In the second branch S3 precedes a nested fork: S5 runs in parallel with the sequential pair S6 then S8. The outer join waits for S4, both S5 and S8, and S7 before permitting S9.
The precedence graph (arrows are immediate dependencies) is:
Its exact edge set is {(S1,S2),(S1,S3),(S1,S7),(S2,S4),(S3,S5),(S3,S6),(S6,S8),(S4,S9),(S5,S9),(S8,S9),(S7,S9)}. This is a transitive reduction: edges such as S1→S9 are implied and need not be drawn. It uses only statement vertices; explicit fork/join vertices would be an equivalent representation.
Do not add S4→S3, S5→S6, or S8→S7: textual order among separate parallel branches does not force execution order. Conversely, S9 must not start after just one branch finishes. The structure imposes control dependencies only; no extra read/write data dependencies are supplied.
What property must a process precedence graph have to be expressed using only properly nested parbegin/parend and sequential composition?
Answer & solution
Answer: It must admit a series-parallel decomposition (no official key was published)
A sequential composition places every process in one component before every process in the next. A parbegin/parend composition runs its child components independently and joins after all finish. Starting from individual processes and repeatedly applying these two constructions yields the series-parallel class of precedence structures. Conversely, its recursive decomposition directly supplies a nested program. An arbitrary acyclic graph can contain cross-dependencies that cannot be represented by these nested constructs alone without extra synchronization or unnecessary ordering. The statement concerns the precedence relation, allowing omission of redundant transitive edges.
Shared atomic variables: flag[0..2] initially false; turn in {0,1,2}. For process i let j=(i+1) mod 3 and k=(i+2) mod 3. Repeat: flag[i] := true while flag[j] or flag[k]: case turn: j: if flag[j]: flag[i] := false while turn != i: skip flag[i] := true k: if flag[k]: flag[i] := false while turn != i: skip flag[i] := true critical section if turn == i: turn := j flag[i] := false noncritical section Does this scheme ensure mutual exclusion? Explain.
Answer & solution
Answer: Yes, under atomic reads/writes and sequential consistency; this does not guarantee progress. (no official key was published)
First separate safety from liveness. A process sets its flag true before testing the outer while condition, and a process admitted to its critical section keeps that flag true until after leaving the critical section. Withdrawing its flag happens only inside the entry loop, never while it is in the critical section.
Suppose two distinct processes p and q were simultaneously in their critical sections. Consider the final assignments flag[p]=true and flag[q]=true preceding these particular admissions. Assume p's assignment occurred first. Its flag remains true from that assignment through its critical section: if it had withdrawn and raised the flag again, the assignment chosen was not final. Process q performs its successful outer test after its own final assignment, hence after p's final assignment. If q enters while p is still inside, q must encounter flag[p]=true and cannot pass the test. If p has already left when q reads false, the two critical sections do not overlap. This contradiction proves mutual exclusion. The argument works with separate atomic flag reads as well: a continuously true competing flag cannot be read as false.
The turn variable controls who backs off, but the persistent true flag is the safety invariant. No fairness assumption is needed for this safety proof. Atomic coherent shared-memory operations are needed; the bare pseudocode is not automatically a correct implementation on a weak-memory machine without suitable synchronization.
Shared atomic variables: flag[0..2] initially false; turn in {0,1,2}. For process i let j=(i+1) mod 3 and k=(i+2) mod 3. Repeat: flag[i] := true while flag[j] or flag[k]: case turn: j: if flag[j]: flag[i] := false while turn != i: skip flag[i] := true k: if flag[k]: flag[i] := false while turn != i: skip flag[i] := true critical section if turn == i: turn := j flag[i] := false noncritical section Can a waiting process fail forever to enter? Give an execution and a corrected algorithm.
Answer & solution
Answer: Yes. Two contenders can spin forever when turn names an inactive third process. A three-process bakery lock is a correct replacement. (no official key was published)
Take turn=2, with process 2 remaining in its noncritical section and flag[2]=false. Let processes 0 and 1 both set their flags true before either completes its outer test. Each sees the other's true flag. Its case selects process 2, but the guarded branch sees flag[2]=false, so neither process withdraws or changes turn. They repeat forever, even under fair scheduling of all active processes. Only a critical-section exit changes turn, and neither contender can reach such an exit. Thus progress fails, not merely a timing bound. An inner waiter can also be stranded when turn is handed to an inactive process.
A safe repair is to replace the entire entry/exit protocol with Lamport's bakery algorithm, rather than merely skipping a false flag: false can mean a temporarily withdrawn waiter, not an uninterested process. Use separate choosing and ticket arrays, initially false and zero. Atomic reads/writes and sequential consistency are assumed, and mathematical tickets are unbounded integers.
For process i:
choosing[i] := true
ticket[i] := 1 + max(ticket[0], ticket[1], ticket[2])
choosing[i] := false
for r := 0 to 2, r != i:
while choosing[r]: skip
while ticket[r] != 0 and (ticket[r],r) < (ticket[i],i): skip
critical section
ticket[i] := 0
noncritical section
repeat
Pairs are compared lexicographically, first by ticket and then process number. The choosing flag prevents observing a half-completed ticket selection as if the process were absent. If two processes competed to enter, the one with larger pair must wait for the smaller pair's nonzero ticket; both cannot be inside together. A process which starts choosing after i has published its ticket obtains a larger ticket and cannot overtake i. Only finitely many already competing choices can precede i. Under fair scheduling, finite ticket-selection and critical-section execution, and no process failures, those predecessors finish, so i eventually enters. An inactive process has choosing=false and ticket=0 and is ignored. These assumptions are necessary: no software lock can promise entry if its current owner stops forever.