🎓 BookMCQ
← Back to 5. Process Synchronization

📝 Pthreads Synchronization in Operating System (36 MCQs)

POSIX Synchronization Primitives for Concurrent Threads

Pthreads synchronization provides standard POSIX mechanisms for coordinating concurrent execution and protecting shared data. Its facilities include mutexes, condition variables, read-write locks, barriers, and semaphores. These interfaces allow application threads to establish mutual exclusion, wait for events, coordinate execution phases, and control access to shared resources without implementing low-level atomic instructions themselves.

Why Concurrent POSIX Programs Need Coordination

Multiple threads within one process normally share global variables, heap memory, and other resources. Unprotected concurrent updates may produce inconsistent results, while dependent operations may execute in the wrong order. Pthreads synchronization primitives provide controlled locking, blocking, notification, and group coordination, allowing application developers to express safe relationships between concurrent activities.

Mutexes, Condition Variables, Semaphores, and Barriers

A pthread mutex provides exclusive access to shared data through pthread_mutex_lock() and pthread_mutex_unlock(). Condition variables use pthread_cond_wait() and pthread_cond_signal() to coordinate waiting threads with a mutex. POSIX semaphores manage permits, read-write locks allow shared reading, and barriers make participating threads wait until a required group reaches the same execution point.

Coordinating Two Threads Updating a Shared Counter

Suppose two Pthreads each increment a shared counter 500 times. Both use pthread_mutex_lock() before modifying the counter and pthread_mutex_unlock() afterward. The mutex prevents overlapping updates, ensuring that the final result is 1,000. Without synchronization, concurrent read-modify-write operations could overwrite one another and produce a lower value.

Concurrency Safety, Blocking Costs, and Deadlock Risks

Pthreads synchronization supports portable server applications, scientific programs, and multithreaded utilities. Mutexes protect shared structures, while condition variables avoid continuous polling. However, incorrect condition checking can cause lost progress, and inconsistent lock ordering can create deadlocks. Excessive locking reduces parallelism, so synchronization scope and duration should remain appropriate.

Misconceptions About Pthreads Synchronization

'pthread_cond_signal() releases a mutex automatically' is incorrect because the waiting thread reacquires its associated mutex before returning from pthread_cond_wait(). 'A barrier protects shared variables automatically' is incorrect because it coordinates arrival but does not provide general mutual exclusion. 'A mutex prevents deadlock in every program' is incorrect because lock ordering can still create circular waits.

Exam Focus: POSIX Locking and Condition-Variable Sequences

Trace mutex acquisition and release, condition-variable waiting, semaphore permits, and barrier arrival. Explain why pthread_cond_wait() atomically releases its mutex while waiting and reacquires it before returning. Questions may compare mutexes with semaphores, identify race conditions, and diagnose incorrect locking or condition-variable usage.

Key Terms of Pthreads Synchronization

  • pthread_mutex_lock() - Acquires a POSIX mutex.
  • pthread_mutex_unlock() - Releases a POSIX mutex.
  • Condition variable - Coordinates conditional thread waiting.
  • Barrier - Waits for participating threads to arrive.
  • Read-write lock - Supports concurrent reads and exclusive writes.
  • Semaphore - Manages available synchronization permits.
12
Easy
12
Medium
12
Hard

📝 All Pthreads Synchronization in Operating System MCQs

Q1. A telemetry service starts two POSIX threads. Each thread increments the same shared counter 500 times, and every increment is enclosed by a successful lock and unlock of the same mutex. What final value should the counter contain?

A.500
B.1000 ✅
C.1500
D.The value is nondeterministic even with the mutex
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Both threads perform 500 increments, giving 500 + 500 = 1,000. Because every read-modify-write operation uses the same mutex, the increments cannot overlap and overwrite one another. Both workers use that identical lock object.

Q2. A controller creates a worker with pthread_create(). The worker writes a result and exits; the controller must use that result before continuing. Which action provides a reliable completion point?

A.Sleep for an estimated execution time
B.Read the result repeatedly until it changes
C.Call pthread_join() for the joinable worker ✅
D.Create another worker and assume the first has finished
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: pthread_join() waits until the specified joinable thread terminates. The caller can then use its result. A timed sleep provides no completion guarantee because scheduling and workload duration can vary. This avoids guessing about operating-system scheduling delays.

Q3. A payment thread updates an account balance, a transaction count, and a checksum. Other threads must never observe a combination from halfway through this update. Which design best protects the invariant?

A.Guard the complete group of related updates and reads with one shared mutex ✅
B.Use an atomic increment only for the transaction count
C.Mark all three fields volatile and access them without locking
D.Give each thread a different mutex for the same account fields
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: The invariant spans several fields, so protecting only one scalar is insufficient. All accesses that rely on the combined state must follow the same synchronization protocol, typically using one mutex around the compound operation.

Q4. A student checks a shared queue count without locking, then calls pthread_cond_wait() only if the count is zero. The producer changes the count and signals between the check and the wait. Which step is flawed?

A.The producer is never allowed to signal a condition variable
B.The condition variable should be replaced by a barrier
C.The queue count must be copied into a thread-local variable
D.The predicate check and update are not coordinated using the same mutex protocol ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The student checks the predicate outside its protecting mutex, allowing the producer to change it and signal before the waiter actually waits. Both predicate inspection and modification must use the associated mutex.

Q5. A program declares a statically allocated default mutex and needs it initialized before any thread uses it. Which initializer is designed for this purpose?

A.PTHREAD_MUTEX_INITIALIZER ✅
B.PTHREAD_COND_INITIALIZER
C.PTHREAD_CREATE_JOINABLE
D.PTHREAD_BARRIER_SERIAL_THREAD
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: PTHREAD_MUTEX_INITIALIZER statically initializes a mutex with default attributes. It is suitable for a static mutex object; dynamically allocated mutexes should instead be initialized with the appropriate initialization function. The object must be initialized before concurrent access begins.

Q6. A logging thread calls pthread_mutex_trylock() while another thread owns the mutex. What should the logging thread expect when the lock is unavailable?

A.It must block until the mutex is released
B.The call returns immediately with a busy result such as EBUSY ✅
C.The mutex is automatically transferred to the caller
D.The call destroys the mutex and recreates it unlocked
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: pthread_mutex_trylock() does not wait for an occupied mutex. It returns an error indicating that the lock is busy, allowing the caller to perform other work or use a deliberate retry strategy.

Q7. A server begins shutdown by destroying a mutex while another worker may still be blocked trying to acquire it. Why is this shutdown sequence invalid?

A.A mutex can only be destroyed by the thread that initialized it
B.A mutex must remain locked permanently after initialization
C.The object may still be in use or referenced by waiters, making destruction undefined or invalid ✅
D.Destroying a mutex automatically wakes every waiter safely
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: A synchronization object must not be destroyed while threads are locking it, waiting on it, or otherwise using it. Shutdown should first stop and join relevant workers, then destroy the unused object.

Q8. A student acquires a normal Pthreads mutex in a worker, but the main thread later calls pthread_mutex_unlock() on that mutex without owning it. Which conclusion is correct?

A.The unlock is safe because any thread may release any mutex
B.The main thread inherits ownership when it starts shutdown
C.The unlock converts the mutex into a semaphore
D.The caller must own the mutex; unlocking a mutex it does not own is invalid ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: A mutex is an ownership-based exclusion mechanism. The thread that unlocks it must satisfy the mutex ownership rules; another thread cannot safely release it merely because it wants the protected region to become available.

Q9. A server measures completed requests per second as worker count increases. The observations are: (1, 1,000), (2, 1,850), (4, 3,100), (8, 3,250), (16, 2,900), where each pair is (workers, requests per second). Which conclusion is best supported?

A.Throughput peaks at 8 workers and falls when the count rises to 16 ✅
B.Throughput doubles every time the worker count doubles
C.The measurements prove that no mutex contention exists
D.One worker always provides the highest throughput
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: The largest measured throughput is 3,250 requests per second at 8 workers. Increasing the count to 16 reduces throughput to 2,900, suggesting contention or coordination overhead can outweigh added parallelism.

Q10. A developer replaces a blocking mutex with a spinlock in a service. Profiling shows that the lock holder is sometimes descheduled while many other threads repeatedly test the lock. What is the main risk?

A.A spinlock automatically sleeps every waiting thread
B.Waiters can waste processor time spinning while the descheduled owner cannot release the lock ✅
C.The lock permits all waiters to enter the critical section together
D.A spinlock guarantees fair acquisition among threads
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: A spinlock consumes CPU while waiting. If its owner is preempted, contenders may burn processor cycles without progress, so a blocking mutex is often preferable when contention or wait duration is significant.

Q11. A worker calls pthread_cond_wait(&cv, &mutex) while holding mutex. What does this operation do as part of its normal wait protocol?

A.It permanently destroys the mutex
B.It keeps the mutex locked until another thread signals
C.It atomically releases the mutex while waiting, then reacquires it before returning ✅
D.It transfers the mutex directly to the signaling thread
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: pthread_cond_wait() atomically releases the supplied locked mutex as it begins waiting. When awakened, it reacquires that mutex before returning, allowing the caller to inspect the shared predicate safely. The caller resumes with exclusive access restored.

Q12. A consumer waits for items in a shared queue. After it is signaled, another consumer may remove the only item before the first consumer reacquires the mutex. Which waiting pattern is correct?

A.Use an if statement and assume every signal reserves an item
B.Wait without holding any mutex
C.Exit the process whenever a condition wait returns
D.Recheck the queue-empty predicate in a while loop while holding the mutex ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: A wakeup only indicates that the predicate may have changed; it does not reserve a queue item. Rechecking the predicate in a loop handles spurious wakeups and cases where another consumer acts first.

Q13. A task scheduler has several worker threads waiting on one condition variable. A producer adds one task and calls pthread_cond_signal(). What is the intended effect?

A.Every thread in the process is resumed
B.One waiting thread is made eligible to resume ✅
C.The condition variable stores a permanent task token
D.The producer automatically releases every mutex in the process
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: pthread_cond_signal() wakes one thread waiting on the specified condition variable, if one is waiting. It does not select which waiter must run, and the awakened thread still reacquires its mutex.

Q14. A producer changes a queue predicate while holding no mutex and then signals the condition variable. A waiting consumer can miss progress. What correction addresses the underlying race?

A.Protect the predicate update and the consumer check with the same associated mutex ✅
B.Replace pthread_cond_signal() with pthread_detach()
C.Call pthread_cond_destroy() immediately after every signal
D.Increase the number of worker threads without changing synchronization
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: A condition notification is not a stored event. The shared predicate must be protected by the mutex associated with waiting, so a consumer cannot check an old value and miss the transition before sleeping.

Q15. A worker uses pthread_cond_timedwait() with an absolute deadline that has already expired. The call returns ETIMEDOUT. What state should the worker expect for the supplied mutex on return?

A.The mutex has been destroyed
B.The mutex remains unlocked until another signal
C.The mutex has been reacquired by the calling thread ✅
D.The mutex is owned by the thread that last signaled the condition
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: A timed condition wait reacquires its associated mutex before returning, including on timeout. The caller should therefore examine the predicate and handle ETIMEDOUT while following the normal mutex-protected protocol. A timeout does not change this reacquisition rule.

Q16. A thread calls pthread_cond_signal() when no thread is waiting. A consumer begins waiting later, but the producer does not signal again. Why might the consumer remain blocked?

A.A condition variable retains every signal until the next process restart
B.The signal changes the condition variable into a mutex
C.The consumer is guaranteed to observe the earlier signal after joining
D.A condition-variable signal is not a persistent permit when no waiter exists ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: Condition variables notify current waiters rather than store event counts. The program must represent durable state in a predicate protected by a mutex, then have waiters check that predicate before sleeping.

Q17. A shared configuration service uses a Pthreads read-write lock. Several clients only inspect the configuration, while an update thread replaces it. Which access rule does the lock express?

A.Multiple readers may hold read access together, but a writer requires exclusive access ✅
B.Readers and writers may always hold the lock concurrently
C.Only the thread that created the lock may read the configuration
D.A writer can hold the lock only when every reader is also holding it
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: A read-write lock allows concurrent read ownership while excluding writers. A writer obtains exclusive access, preventing both other writers and readers from accessing the protected region during the update. Readers coexist only while no writer owns it.

Q18. A web cache uses a read-write lock because lookups are frequent and updates are rare. What is the key trade-off compared with a single mutex?

A.A read-write lock eliminates all synchronization overhead
B.It can increase read concurrency, but has additional management cost and does not guarantee faster performance for every workload ✅
C.It allows several writers to modify the cache simultaneously
D.It automatically makes the cache data immutable
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Read-write locks can improve concurrency when reads dominate and critical sections are suitable for sharing. Their bookkeeping and fairness behavior add costs, so a simple mutex may perform better for short or write-heavy workloads.

Q19. A benchmark records completed cache reads per second under a read-write lock: (1, 900), (2, 1,700), (4, 3,000), (8, 4,200), (16, 4,300), where each pair is (reader threads, reads per second). Between which consecutive thread counts is the largest absolute gain?

A.1 to 2 readers
B.4 to 8 readers
C.2 to 4 readers ✅
D.8 to 16 readers
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: The gains are 800, 1,300, 1,200, and 100 reads per second. The largest increase is 1,300 between 2 and 4 readers, while the later values show diminishing returns. Subtract each earlier measurement from the next one.

Q20. A parallel image-processing program creates 6 worker threads. Each worker must finish its current tile before any worker starts the next phase. Which Pthreads primitive directly coordinates this arrival point?

A.A mutex used only by the main thread
B.A thread-specific data key
C.A detached thread attribute
D.A barrier initialized for six participants ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: A barrier makes each participating thread wait until the configured number of participants has arrived. With six workers, the barrier count should match those six arrivals for the phase transition.

Q21. Six threads reach a barrier before updating a shared statistics structure. A developer assumes the barrier alone prevents simultaneous writes to that structure. What is wrong with this reasoning?

A.A barrier coordinates phase arrival but does not provide general mutual exclusion for later shared updates ✅
B.A barrier always permits only one thread to execute after release
C.A barrier automatically converts ordinary variables into atomic variables
D.A barrier can only be used by threads in different processes
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: A barrier synchronizes when participants may proceed; it does not serialize all code after release. Concurrent updates to shared statistics still need a mutex, atomics, or another suitable protection strategy.

Q22. Several threads call an initialization function for a shared routing table. Which Pthreads mechanism ensures the routine is executed once for a particular once-control object?

A.pthread_barrier_wait()
B.pthread_once() ✅
C.pthread_mutex_trylock()
D.pthread_cond_broadcast()
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: pthread_once() coordinates concurrent callers so the associated initialization routine executes exactly once for its once-control object. Callers return from the mechanism only after the one-time initialization has completed. This prevents concurrent threads from running duplicate setup.

Q23. Two processes need to coordinate through an unnamed POSIX semaphore stored in a shared-memory region. Which initialization choice is required for interprocess sharing?

A.Set the process-shared argument to zero and keep the semaphore in private memory
B.Use pthread_once() instead of sem_init()
C.Set the process-shared argument to nonzero and place the semaphore in memory shared by both processes ✅
D.Initialize the semaphore separately in each process at unrelated addresses
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: For an unnamed POSIX semaphore shared across processes, sem_init() must receive a nonzero process-shared argument. The semaphore object must also reside in a memory region mapped and shared by both processes.

Q24. A resource pool initializes an unnamed counting semaphore to 4 permits. A client successfully calls sem_wait() twice and then another client calls sem_post() once. What is the resulting permit count?

A.4
B.5
C.6
D.3 ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: Each successful sem_wait() consumes one permit, so the count changes from 4 to 2. One sem_post() adds a permit, producing 2 + 1 = 3 available permits. The semaphore count tracks permits remaining for later acquisitions.

Q25. A database connection pool uses a counting semaphore for free connections and a mutex for a linked list containing connection metadata. Why are both synchronization objects useful?

A.The mutex tracks the number of available connections while the semaphore protects every list pointer
B.The semaphore makes linked-list updates indivisible without a mutex
C.The mutex allows several threads to remove the same connection concurrently
D.The semaphore tracks available permits, while the mutex protects compound updates to the metadata list ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The counting semaphore represents how many connections can be acquired. The mutex protects consistency of the linked list and related fields; each primitive addresses a different part of the coordination problem.

Q26. A thread calls sem_post() when the semaphore value is zero and no thread is waiting. Another thread calls sem_wait() later. What happens to the posted permit?

A.It disappears exactly like a condition-variable signal with no waiter
B.It wakes every thread in the process
C.It remains represented in the semaphore count and can satisfy the later wait ✅
D.It is converted automatically into a mutex ownership record
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: A semaphore maintains a count of permits. A post increments that count even when no waiter exists, so a later successful wait can consume the stored permit; condition-variable signals do not work this way.

Q27. A resource manager records its semaphore value over time as (0 s, 4), (1 s, 2), (2 s, 0), (3 s, 0), (4 s, 1), (5 s, 3), where each pair is (time, permits). During which interval is the semaphore continuously depleted?

A.From 0 to 1 seconds
B.From 2 to 3 seconds ✅
C.From 3 to 4 seconds
D.From 4 to 5 seconds
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The recorded value is zero at both 2 seconds and 3 seconds, so no permits are available throughout that interval. It becomes positive at 4 seconds when a permit is posted.

Q28. A thread is canceled while blocked inside pthread_cond_wait(). Its cleanup handler is responsible for unlocking the mutex passed to the wait. What should the handler expect under the Pthreads cancellation protocol?

A.The mutex has been reacquired before the cleanup handler executes ✅
B.The mutex was permanently destroyed by cancellation
C.The mutex belongs to the signaling thread
D.The cleanup handler must call pthread_join() on itself
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: When cancellation occurs during a condition wait, the waiting thread reacquires the mutex before cleanup handlers run. A cleanup handler can therefore release it, provided the program has registered and structured the handler correctly.

Q29. A worker registers a cleanup handler that always unlocks a mutex, but an error path can invoke cancellation before the worker has acquired that mutex. What must the design change?

A.Make the cleanup handler lock every mutex in the process
B.Destroy the mutex before registering the handler
C.Ignore the ownership state because unlock is idempotent
D.Track whether acquisition succeeded and unlock only when the worker actually owns the mutex ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: A cleanup handler must reflect the resource state at cancellation time. Unlocking a mutex that the thread never acquired is invalid, so registration order or an ownership flag must ensure cleanup matches successful acquisition.

Q30. A program calls pthread_detach() for a worker whose result will not be collected. Which statement describes the resulting thread lifecycle?

A.The main thread must still join it to release its resources
B.Its resources are reclaimed automatically when it terminates, and it cannot subsequently be joined ✅
C.It becomes a process-shared thread
D.It can no longer acquire mutexes or condition variables
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Detaching marks a thread as nonjoinable. Its resources are reclaimed after termination without a join operation, and the application gives up the normal pthread_join() completion and result-retrieval path. The detached thread continues executing normally until it exits.

Q31. A developer uses an atomic increment for a shared request count and assumes that the increment also makes a separate request-details structure safe for simultaneous updates. Which statement is correct?

A.Every atomic operation protects all objects allocated nearby
B.The details structure is safe whenever its address is aligned
C.Atomicity of one counter operation does not protect a separate compound data structure ✅
D.Atomic variables remove the need for all mutexes in a program
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: An atomic increment guarantees indivisibility for that atomic object, not for unrelated fields or a multi-step invariant. The request-details structure needs its own appropriate synchronization protocol. Related data still requires a lock or a correct atomic protocol.

Q32. A producer writes a payload and then stores ready = 1 using a release atomic operation. A consumer loads ready with acquire semantics and observes 1 before reading the payload. Why is this pairing useful?

A.It establishes ordering so the payload writes become visible to the observing consumer ✅
B.It makes the payload private to the producer
C.It guarantees that the consumer runs on the same CPU core
D.It converts the ready flag into a counting semaphore
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: When the acquire load observes the release store, the synchronization relationship orders the producer preceding writes before the consumer reads. This safely publishes the payload, assuming the flag protocol is otherwise correct.

Q33. Two worker threads acquire two mutexes. Thread A locks L1 and then requests L2; thread B locks L2 and then requests L1. Both retain their first lock while waiting. What is the central design flaw?

A.The program uses two mutexes instead of one condition variable
B.Each mutex must be initialized by both threads independently
C.The second lock request should always be nonblocking
D.The inconsistent acquisition order permits a circular wait; impose one global lock order ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: Thread A can hold L1 while waiting for L2, and thread B can hold L2 while waiting for L1. A consistent global acquisition order prevents this circular-wait pattern. Every thread using both locks must follow the same rule.

Q34. A database service measures throughput as the time spent inside a shared critical section changes. The observations are (1 ms, 950), (2 ms, 880), (4 ms, 720), (8 ms, 430), (16 ms, 220), where each pair is (critical-section duration, transactions per second). Between which consecutive durations is the largest throughput drop?

A.1 ms to 2 ms
B.2 ms to 4 ms
C.4 ms to 8 ms ✅
D.8 ms to 16 ms
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: The successive throughput drops are 70, 160, 290, and 210 transactions per second. The largest decrease is 290, occurring as the protected duration rises from 4 ms to 8 ms.

Q35. A bounded connection queue has capacity 3. Its slots semaphore starts at 3 and its items semaphore at 0. Which producer sequence correctly reserves capacity, updates the queue, and announces a new item?

A.Lock the queue mutex, wait on items, insert, then unlock the mutex
B.Wait on slots, lock the queue mutex, insert, unlock the mutex, then post items ✅
C.Post items before inserting, then wait on slots while holding the mutex
D.Wait on items, insert without the mutex, then post slots
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The producer first consumes a free-slot permit, then protects the queue insertion with its mutex. After unlocking, it posts an item permit so a consumer can safely claim the newly available item.

Q36. A queue consumer uses a mutex and a condition variable. After a broadcast, two consumers wake, but only one item is available; the first consumer removes it before the second reacquires the mutex. What must the second consumer do?

A.Recheck the empty predicate while holding the mutex and wait again if it is true ✅
B.Remove an item anyway because broadcast reserves one for each waiter
C.Unlock the mutex permanently and continue with an uninitialized item
D.Assume a broadcast makes the queue count equal to the number of consumers
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: A broadcast wakes all current waiters but does not reserve resources for them. The second consumer must reacquire the mutex, recheck the queue predicate in a loop, and sleep again if no item remains.

🔗 Related Topics (MCQs)