π 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.
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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.