πŸŽ“ BookMCQ
← Back to 4. Threads in Operating System

πŸ“ Pthreads in operating system (33 MCQs)

POSIX Threading Standard and Application Programming

Pthreads, or POSIX threads, provide a standardised programming interface for creating and managing threads in POSIX-compliant environments. The interface supports thread creation, termination, joining, detachment, mutexes, condition variables, and thread attributes. It enables applications to organise concurrent work using defined function calls while leaving the underlying kernel-thread implementation to the operating system.

Why Portable POSIX Thread Interfaces Are Needed

Applications that use operating-system-specific threading interfaces can become difficult to port across Unix-like environments. POSIX defines common thread operations and synchronisation facilities, reducing dependence on individual implementation details. However, conformance does not guarantee identical scheduling behaviour or performance across systems, and some platform-specific extensions may still affect portability.

pthread_create, pthread_join, and Mutex Operations

An application calls pthread_create() to start a thread using a specified start routine and argument. The new thread executes that function independently. pthread_join() waits for a joinable thread to terminate and can retrieve its return value. Mutex operations such as pthread_mutex_lock() and pthread_mutex_unlock() coordinate access to shared data.

Calculating a Sum Using Two Pthreads

Suppose a program must sum an array of 10,000 integers. The main thread creates two Pthreads, assigning 5,000 elements to each worker. Each worker computes a partial result independently. The main thread calls pthread_join() for both workers and adds their returned sums to obtain the final total.

Concurrency Control, Portability, and Implementation Costs

Pthreads supports portable parallel applications, server software, and numerical computing on POSIX systems. Mutexes and condition variables provide standard coordination mechanisms. However, improper locking can produce deadlocks or race conditions, and frequent thread creation can increase overhead. POSIX specifies interfaces and behaviour, not a single mandatory internal kernel-thread architecture or scheduling performance.

Misconceptions About POSIX Thread Functions

'pthread_create() waits for the new thread to finish' is incorrect because it starts the thread without waiting for completion. 'pthread_join() forcibly terminates a thread' is incorrect because it waits for an already executing thread to terminate. 'Pthreads guarantees identical performance on every system' is incorrect because implementations and hardware differ.

Exam Focus: Pthreads Function Calls and Execution Flow

Understand the roles of pthread_create(), pthread_join(), pthread_exit(), pthread_detach(), and mutex functions. Trace the execution of a main thread and multiple worker threads, including argument passing and return values. Questions may examine race conditions, joining versus detaching, mutex ownership, and the distinction between POSIX interfaces and their kernel implementations.

Key Terms of Pthreads

  • Pthreads - POSIX threading programming interface.
  • pthread_create() - Starts a new POSIX thread.
  • pthread_join() - Waits for thread completion.
  • pthread_exit() - Terminates the calling thread.
  • Mutex - Provides exclusive shared-data access.
  • POSIX - Standard for portable operating interfaces.
11
Easy
11
Medium
11
Hard

πŸ“ All Pthreads in operating system MCQs

Q1. A program needs a worker to calculate a result while the main thread continues accepting input. Which Pthreads operation creates the worker?

A.pthread_create() βœ…
B.pthread_join()
C.pthread_mutex_unlock()
D.pthread_exit()
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: pthread_create() requests a new thread and specifies its start routine and argument. After successful creation, the worker becomes eligible to execute while the calling thread can continue, although scheduling determines which thread runs first.

Q2. Which function type is required for a typical Pthreads start routine?

A.int routine(int value)
B.void routine(void)
C.void *routine(void *argument) βœ…
D.pthread_t routine(pthread_t argument)
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: A Pthreads start routine normally accepts one void pointer argument and returns a void pointer. Using the compatible function type lets the library pass the supplied argument and lets the thread return a value safely.

Q3. Immediately after a successful pthread_create() call, what can the creating thread safely assume about execution order?

A.the new thread must finish before the creator continues
B.the creator always runs until it calls pthread_join()
C.the new thread always runs first on another core
D.the scheduler may run either the creator or the new thread first βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: Successful creation makes the new thread eligible, but it does not establish a fixed execution order. The creator may continue first, or the new thread may run immediately, so required ordering needs synchronization.

Q4. The main thread needs to wait for a joinable worker and collect the pointer returned by its start routine. Which operation should it use?

A.pthread_detach()
B.pthread_join() βœ…
C.pthread_cancel()
D.pthread_mutex_destroy()
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: pthread_join() waits for the specified joinable thread to terminate and can collect its returned pointer value. It is appropriate when the caller needs both completion synchronization and access to the worker result.

Q5. A program creates a thread without supplying a detached-state attribute. What is the usual initial state of a newly created Pthreads thread?

A.detached
B.cancelled
C.joinable βœ…
D.blocked permanently
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Pthreads threads are normally created joinable unless attributes request detached state. A joinable thread retains termination information until another thread joins it, allowing completion synchronization and retrieval of its return value.

Q6. A background worker performs maintenance and its result is not needed by any other thread. Which lifecycle choice allows its termination resources to be reclaimed automatically?

A.make the worker detached βœ…
B.join the worker before it begins
C.keep the worker permanently joinable
D.call pthread_mutex_destroy() on its identifier
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: A detached thread does not require another thread to join it. When it terminates, its implementation can reclaim its thread resources automatically, which suits workers whose termination result is not needed by the application.

Q7. A worker calls pthread_exit() after finishing its task. What is the direct effect of this call?

A.it terminates every thread in the process
B.it joins all threads created by the worker
C.it detaches the calling thread but keeps it running
D.it terminates the calling thread and supplies an exit value if provided βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: pthread_exit() ends the calling thread rather than acting as a join or detach operation. Other process threads may continue, and a joinable thread’s termination value can be collected by a thread that joins it.

Q8. A thread start routine finishes by returning a pointer value. How is this termination treated by Pthreads?

A.the process is necessarily terminated
B.returning from the start routine is equivalent to calling pthread_exit() with that value βœ…
C.the pointer is automatically freed
D.the thread becomes detached before returning
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: Returning from a Pthreads start routine terminates that thread as though pthread_exit() had been called with the returned value. A joiner can collect the value, but memory ownership remains the application’s responsibility.

Q9. A program checks the result of pthread_create(). Which interpretation is correct?

A.zero indicates success, while a nonzero return indicates an error code βœ…
B.zero indicates failure, while errno always contains the error
C.a positive result is the new thread identifier
D.the function never reports creation failures
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: pthread_create() returns zero on success and an error number on failure. The program should inspect this return value directly rather than assuming the usual errno mechanism has been used to report the error.

Q10. Two Pthreads workers update a shared structure. Which basic mutex discipline protects the critical section?

A.destroy the mutex before accessing the structure
B.lock the mutex after completing the update
C.lock before the protected update and unlock after the update βœ…
D.use pthread_join() instead of every mutex operation
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: A mutex protects shared data when a thread acquires it before entering the critical section and releases it after the update. Other cooperating threads must follow the same protocol to avoid conflicting access.

Q11. A consumer must sleep until a producer inserts an item into a shared queue. Which Pthreads combination is appropriate?

A.a detached thread and an unsynchronized flag
B.a condition variable used with a mutex and a predicate-checking loop βœ…
C.pthread_exit() called repeatedly by the consumer
D.pthread_cancel() used as a notification
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: The mutex protects the queue and its nonempty predicate, while a condition variable lets the consumer wait without busy polling. The consumer must recheck the predicate after waking because wake-ups do not guarantee an item remains available.

Q12. A worker receives a pointer to a counter through pthread_create(). The creating function returns while the worker may still use the counter. What must be ensured?

A.the pointer is converted to a thread identifier
B.the worker never reads the counter
C.the counter is copied automatically by pthread_create()
D.the pointed-to storage remains valid for the worker’s entire access period βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The argument is passed as a pointer, not copied into independent storage automatically. Its target must remain alive while the worker accesses it; shared modifications also require synchronization to avoid data races.

Q13. A worker returns the address of an automatic local variable, and the main thread retrieves it with pthread_join(). Why is dereferencing it unsafe?

A.joining does not extend the local variable’s lifetime beyond the function return βœ…
B.pthread_join() changes every pointer into a thread identifier
C.Pthreads forbids returning pointer values
D.the local variable is copied into the main thread’s stack automatically
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: An automatic local variable ceases to exist when its function returns. pthread_join() collects the pointer but does not extend the object’s lifetime, so the result may point to invalid storage and must not be dereferenced.

Q14. A worker allocates a result on the heap and returns its address. After pthread_join() retrieves the pointer, what must the receiving application do?

A.assume pthread_join() has already freed the allocation
B.free the memory before reading any result fields
C.manage ownership and release the allocation exactly once when it is no longer needed βœ…
D.keep the allocation forever because returned pointers cannot be freed
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: pthread_join() returns the pointer value but does not free the pointed-to allocation. The application must define who owns the result, keep it valid while reading it, and free it exactly once afterward.

Q15. A program creates four independent workers using pthread_create() before joining them one by one. What is true about their execution?

A.the first join prevents the other workers from starting
B.the workers may execute concurrently even though the main thread performs joins sequentially βœ…
C.each join merges one worker into the main thread
D.the workers are forced to execute in creation order
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: Workers become eligible when created, so they may overlap in execution before the main thread begins or completes its joins. Sequential join calls control the main thread’s waiting sequence, not worker execution order.

Q16. A worker holds a mutex while updating shared data, then returns without unlocking it. Other workers block when they try to acquire the same mutex. What caused the problem?

A.pthread_join() automatically locked the mutex
B.the mutex was converted into a condition variable
C.the operating system destroyed the shared data
D.the worker left the mutex locked, preventing other threads from acquiring it βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The worker failed to complete the locking protocol. Returning while holding a normal mutex can leave other threads blocked indefinitely; cleanup and control flow should ensure the lock is released safely before termination.

Q17. A thread locks the same normal non-recursive mutex twice without unlocking between calls. What may happen on the second lock attempt?

A.the thread may block waiting for a mutex it already owns βœ…
B.the mutex automatically creates a second lock instance
C.the first lock is silently released
D.the calling thread is converted into a detached thread
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: A normal non-recursive mutex is not intended to be acquired repeatedly by its owner. Attempting to lock it again can block the thread indefinitely, so the program should avoid recursive acquisition or deliberately select a suitable mutex type.

Q18. A consumer waits on a condition variable because a queue is empty. It wakes after a signal, but another consumer has already removed the item. What should the first consumer do?

A.continue as though the item must still exist
B.terminate the producer
C.recheck the queue predicate while holding the mutex and wait again if it is false βœ…
D.destroy the condition variable immediately
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: A condition-variable signal does not reserve an item for the awakened consumer. Another consumer may change the queue before it reacquires the mutex, so the predicate must be checked again in a loop.

Q19. A program wants to destroy a mutex after all workers finish. Which condition should hold before pthread_mutex_destroy() is called?

A.the mutex must be locked by the main thread
B.the mutex is no longer locked or in use by any thread βœ…
C.all worker identifiers must be converted to pointers
D.the mutex must have protected at least one update
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: A mutex should be destroyed only after its users have finished and it is in an appropriate unlocked state. Destroying a locked or concurrently accessed mutex can produce errors or undefined behavior.

Q20. A program cancels a worker that may be holding a mutex. What should its design account for?

A.cancellation automatically rolls back every shared-memory update
B.pthread_cancel() is identical to pthread_join()
C.a cancelled worker always releases every application lock regardless of cancellation state
D.cleanup may be needed to release resources and preserve shared-data invariants βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: Cancellation behavior depends on the thread’s cancellation state, type, and cancellation points. If cancellation occurs while resources are held or data is being changed, cleanup must prevent locked mutexes and inconsistent application state.

Q21. A program changes a pthread attribute object’s stack-size setting after a worker has already been created. What should the programmer expect?

A.the existing worker’s allocated stack generally remains unchanged βœ…
B.the worker’s stack immediately doubles
C.all running threads adopt the new stack size
D.the worker automatically restarts with the new attribute
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: Thread attributes are generally applied when a thread is created. Modifying the attribute object afterward configures future creations but does not retroactively resize the stack or change resources already allocated to an existing worker.

Q22. Six workers each process 20 independent tasks requiring 2 ms of CPU time per task. With six effective cores and no overhead, what is their ideal completion time?

A.120 ms
B.20 ms
C.6 ms
D.40 ms βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: Each worker performs 20 tasks, requiring 40 ms of CPU time. The six workers can run concurrently on six effective cores, so the ideal total time is 40 ms, assuming balanced independent work and no overhead.

Q23. A program passes an integer identifier to pthread_create() by converting the integer directly to void *. Which alternative is safer and more portable?

A.pass the address of valid storage containing the integer and read it through the correct type βœ…
B.pass the address of a local variable that disappears before the worker starts
C.cast any integer to a pointer and dereference it on every platform
D.store the integer in the worker’s function address
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: A pointer to valid storage with a suitable lifetime avoids relying on implementation-specific integer-to-pointer conversions. The worker can retrieve the value using the correct type, provided the storage remains valid until access finishes.

Q24. A Pthreads program passes a function to pthread_create(), but the function takes an int and returns int instead of using the required start-routine type. What is the proper correction?

A.cast the function pointer and assume the calling convention will match
B.change the function to the compatible void * function(void *) form or use a correctly typed wrapper βœ…
C.pass the function address as the argument pointer
D.ignore compiler diagnostics because the function runs in a new thread
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: The start routine must have a compatible function-pointer type, typically returning void pointer and accepting one void pointer argument. A correctly typed wrapper can adapt other interfaces; an incompatible function pointer is not made safe by casting.

Q25. The main thread creates a worker and then calls pthread_exit() instead of returning from main. What is the intended effect?

A.it joins the worker and collects its return value automatically
B.it detaches every thread in the process
C.it terminates the calling main thread while allowing other threads to continue, subject to process-lifetime rules βœ…
D.it cancels every thread created before the call
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: pthread_exit() terminates the calling thread, not directly every other thread. Other process threads may continue executing independently, but the process ends when its remaining threads also terminate under the normal process-lifetime rules.

Q26. A worker calls pthread_join() using its own thread identifier as the target. What is the fundamental problem?

A.self-joining creates a duplicate thread identifier
B.the call automatically detaches the worker
C.the worker receives its own return pointer immediately
D.a thread cannot wait for its own termination and may deadlock or receive an error βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: A thread cannot finish while it is blocked waiting for itself to terminate. Self-joining is invalid and may produce an error such as EDEADLK; thread dependencies should require waiting only for another independently completing thread.

Q27. A worker writes a shared result and sets an ordinary Boolean flag. The main thread reads the flag repeatedly without a mutex or atomic operation. What is the central concern in C?

A.the flag is automatically synchronized because both threads share one process
B.the unsynchronized conflicting accesses can create a data race and undefined behavior βœ…
C.ordinary Boolean variables cannot be used in any C program
D.pthread_create() makes every later access to the flag atomic
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: In C, conflicting unsynchronized accesses to an ordinary shared object can constitute a data race when at least one access modifies it. A mutex or appropriate atomic protocol must also establish visibility of the result.

Q28. A worker unlocks a mutex after updating a shared result. The main thread later locks the same mutex before reading that result. What property does this protocol provide?

A.it guarantees that both threads execute on the same core
B.it makes every other shared variable atomic permanently
C.it replaces the need to initialize the mutex
D.the unlock and subsequent lock establish synchronization for the protected update βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: Correct mutex use establishes synchronization between the unlocking thread and a thread that subsequently acquires the same mutex. This supports visibility and exclusion for protected data, provided all conflicting accesses follow the protocol.

Q29. A worker is cancelled while modifying a shared structure and holding a mutex. Which design best protects the program?

A.use appropriate cleanup handling and cancellation discipline so locks are released and shared invariants remain valid βœ…
B.assume cancellation restores the structure to its previous state automatically
C.avoid checking whether cancellation can occur inside the critical section
D.destroy the mutex immediately from another thread
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: Cancellation does not automatically roll back shared writes or guarantee application-level cleanup. The design should control cancellation points and use cleanup handlers or equivalent logic to release held locks and leave shared structures consistent.

Q30. A program joins a worker only after it terminates. During the worker’s execution, another worker reads the same shared variable without synchronization. Does the later join make the earlier concurrent access safe?

A.yes, joining permanently converts shared variables into atomic objects
B.yes, because a worker can only be joined once
C.no, join synchronizes with completion but does not prevent data races that occurred while threads were running βœ…
D.no, because pthread_join() never provides synchronization
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: Joining establishes synchronization with the target thread’s termination, but it cannot retroactively protect conflicting accesses that occurred earlier. Shared variables need appropriate synchronization during concurrent execution, not merely a later join operation.

Q31. A program creates three workers, each requiring 7 ms of independent CPU work. It starts all three, performs 4 ms of independent main-thread work, then joins the workers. With three effective cores and no overhead, when does the program finish?

A.21 ms
B.11 ms
C.25 ms
D.7 ms βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: The three workers run concurrently and complete their 7 ms workloads at time 7. The main thread’s 4 ms of independent work overlaps that interval, so its later join returns at 7 ms rather than adding the durations.

Q32. A developer assumes pthread_join() automatically frees a heap object returned by the worker. What ownership rule should replace this assumption?

A.the joiner owns the result pointer and must release the allocation exactly once when it is no longer needed βœ…
B.the worker must free the object before returning its address
C.the operating system always frees every heap result when a thread exits
D.the pointer must never be dereferenced after a successful join
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: pthread_join() transfers or collects the returned pointer value, not ownership management of the allocation itself. The application must agree who owns the object, keep it valid while used, and free it exactly once.

Q33. A long-running service uses four Pthreads workers. One worker waits for each task to finish, performs cleanup, then accepts another task. Which implementation pattern avoids repeated thread creation while retaining worker availability?

A.call pthread_exit() after every task and expect the same thread to resume
B.cancel the worker after each successful task
C.detach the worker after every task and continue using its identifier
D.keep each worker in a task-processing loop with per-task cleanup before the next task βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: A persistent worker loop performs cleanup for the completed task and then returns to waiting for more work. The thread remains available, avoiding repeated creation and termination while ensuring task-specific resources are released.

πŸ”— Related Topics (MCQs)