📝 Thread libraries in operating system (33 MCQs)
Programming Interfaces for Creating and Managing Threads
Thread libraries provide programming interfaces through which applications create, synchronise, manage, and terminate threads. They belong to the operating system's threading environment and may implement operations through user-space runtime code, kernel facilities, or both. Common facilities include thread creation, joining, detaching, mutexes, condition variables, and thread-specific data, allowing developers to organise concurrent execution systematically.
Why Applications Need Standard Threading Interfaces
Manually managing execution contexts, processor states, and concurrent access is complex and error-prone. Thread libraries hide low-level management details behind standard functions and synchronisation abstractions. They also provide reusable programming interfaces across application components. However, library behaviour and available capabilities depend on the supported threading standard, operating system, and underlying implementation.
Creation, Joining, Synchronisation, and Thread Attributes
An application invokes a thread-creation function with a start routine and its argument. The library establishes the execution context and schedules or registers the thread through the supported implementation. A joining operation waits for termination and may collect its result. Mutexes and condition variables coordinate shared data and communication between execution activities.
Creating and Joining Two Worker Threads
Consider a program that creates two worker threads to calculate separate portions of an array containing 20,000 values. Each thread processes 10,000 elements and returns its partial sum. The main thread joins both workers, collects their results, and adds the partial sums. Joining ensures that the final calculation uses completed worker results.
Portability, Thread Control, and Synchronisation Overhead
Thread libraries simplify concurrent programming and support reusable code for servers, scientific applications, and interactive software. Standardised interfaces can improve portability, but platform-specific extensions may reduce it. Mutex contention, frequent thread creation, and incorrect locking can reduce performance or cause deadlocks. A library also cannot automatically eliminate race conditions in application logic.
Misconceptions About Thread Library Functions
'A thread library always schedules threads entirely in user space' is incorrect because many implementations rely on kernel-supported threads. 'Joining a thread creates another thread' is incorrect because joining waits for an existing thread to finish. 'Using a mutex automatically prevents every concurrency error' is incorrect because incorrect locking can still create races and deadlocks.
Exam Focus: Thread Creation and Synchronisation Interfaces
Identify the purpose of thread creation, joining, detaching, mutex, and condition-variable functions. Trace a program that creates workers, distributes tasks, and collects results. Questions may distinguish user-level from kernel-level thread management, compare library interfaces, and examine how synchronisation protects shared data.
Key Terms of Thread Libraries
- Thread library - Interface for managing concurrent threads.
- Start routine - Function executed by a new thread.
- Join - Waits for thread termination.
- Detach - Releases join-related thread resources.
- Mutex - Lock providing mutual exclusion.
- Condition variable - Coordinates waiting and notification.
📝 All Thread libraries in operating system MCQs
Q1. What is the primary role of a thread library in an application?
📖 Explanation: A thread library exposes programming interfaces for creating threads, waiting for completion, configuring attributes, and coordinating shared data. It simplifies thread management but does not replace the operating system or guarantee separate processors.
Q2. A developer wants a worker to calculate a result while the main thread continues accepting user input. Which library facility is required?
📖 Explanation: Creating a worker thread gives the calculation its own execution path while the main thread handles input. Actual simultaneous execution depends on processor availability and implementation, but creation enables overlapping activities.
Q3. Which statement correctly distinguishes a thread library from the operating system scheduler?
📖 Explanation: A thread library provides application-facing operations for creating and coordinating threads. The operating system scheduler selects kernel-schedulable entities for processor time. Their responsibilities interact, but they remain conceptually distinct responsibilities.
Q4. A program calls a thread-creation function with a start routine and an argument pointer. What does the new thread normally do?
📖 Explanation: A creation operation establishes a new thread whose execution begins at the designated start routine. The supplied argument provides input to that routine, allowing the creator to pass task-specific information to the worker.
Q5. A developer assumes a newly created thread must execute before the creation function returns. Which assessment is safest?
📖 Explanation: A successful creation call generally makes the new thread eligible to run, but the scheduler determines when it receives processor time. The creator or another thread may execute first, so explicit synchronization is needed when order matters.
Q6. A program creates three workers, but the second creation call fails. The main thread later attempts to join all three identifiers without checking return statuses. What is the best correction?
📖 Explanation: Thread creation can fail because of resource limits, invalid attributes, or implementation restrictions. The program should check each return status, record successful creations, and join only valid thread identifiers to avoid invalid waits.
Q7. A worker calculates a result and terminates. The main thread must use that result before continuing. Which operation is most appropriate for a joinable worker?
📖 Explanation: Joining waits until the target thread has terminated and can provide its completion result through the library interface. This ensures the main thread does not consume a partial result while the worker is still calculating.
Q8. A program creates a worker and immediately joins it before doing any independent work. What is the likely consequence?
📖 Explanation: Joining immediately blocks the calling thread until the worker finishes. If the caller has independent work available, waiting first prevents that work from overlapping the computation and can reduce the benefit of creating a separate thread.
Q9. A worker is configured as detached. Which consequence should the application expect?
📖 Explanation: A detached thread is not intended to be joined for its termination result. Its implementation can reclaim associated resources automatically when it exits, so applications needing a join result should use a joinable design.
Q10. A thread finishes its assigned calculation and calls the library's thread-exit operation. What is the intended effect?
📖 Explanation: A thread-exit operation terminates the calling thread and may provide a return value. Other threads in the same process can continue running unless the application or process termination rules cause them to stop.
Q11. A program sets each new worker's stack reservation to 2 MB. A capacity report gives these pairs: (1,2 MB) ; (2,4 MB) ; (4,8 MB) ; (8,16 MB) ; (12,24 MB), where each pair is (thread count, total reserved stack). Which conclusion follows?
📖 Explanation: Each worker adds 2 MB to the reserved total; for example, MB. The pattern describes configured reservation, not actual stack consumption by every worker during execution or peak memory use.
Q12. A thread library provides an attribute for stack size. Why might an application adjust it?
📖 Explanation: Each thread needs stack space for calls, local variables, and related execution data. Reducing its stack can save memory but risks overflow; increasing it supports deeper calls while consuming more address-space resources.
Q13. A thread library lets an application set scheduling attributes for a new thread. What should the programmer avoid assuming?
📖 Explanation: Thread attributes express requested settings, but the implementation and operating system determine which policies are supported and permitted. Applications should check errors and avoid assuming a requested priority or scheduling policy is always honored.
Q14. A program shares a pointer to a local variable with a worker. The creating function returns before the worker reads it. What is the principal risk?
📖 Explanation: The local variable may cease to exist when its creating function returns. If the worker later dereferences the pointer, it can access invalid storage; the data must remain alive until the worker no longer needs it.
Q15. Two workers update the same shared counter without a mutex or atomic operation. The final value is occasionally too small. What explains this result?
📖 Explanation: An increment commonly involves separate read, modify, and write steps. Concurrent interleaving can let both workers read the same old value and then overwrite one another's result, producing a lost update and an incorrect total.
Q16. A server benchmark records worker count and throughput while all workers contend for one mutex: (1,1000) ; (2,760) ; (4,490) ; (8,260) ; (16,130) requests per second. Which trend is most consistent with these measurements?
📖 Explanation: Throughput drops from 1000 to 130 requests per second as workers increase from one to sixteen. This pattern indicates rising contention and serialized access, not increased parallel efficiency under the measured workload.
Q17. A server updates two independent counters from different cores. The counters occupy the same cache line and are frequently modified. Which effect can occur even though the counters are distinct?
📖 Explanation: False sharing occurs when independent variables share a cache line that different cores modify. Coherence protocols may transfer the line repeatedly, reducing performance even though each thread accesses a distinct variable without a data race.
Q18. A producer signals a condition variable after adding an item to a shared queue. Why should a waiting consumer check the queue predicate in a loop after waking?
📖 Explanation: A notification does not guarantee the predicate is still true when the consumer resumes. Spurious wake-ups or competition among consumers can occur, so the condition must be rechecked while protecting the shared queue state.
Q19. A thread waits on a condition variable until a shared queue becomes nonempty. Which synchronization pattern is generally correct?
📖 Explanation: The mutex protects the queue predicate and coordinates the transition into waiting. After waking, the consumer reacquires the mutex and checks again because notification alone does not establish that an item remains available.
Q20. A producer adds one item to a queue and signals a condition variable. Several consumers are waiting. What does a typical signal operation request?
📖 Explanation: A typical condition-variable signal wakes one waiting thread, if any exist. A broadcast operation is used when all waiters should be notified, but each awakened consumer must still recheck the shared predicate under the mutex.
Q21. A worker writes a shared result and then reports completion. The main thread sometimes sees an older value after receiving a notification. What should be examined?
📖 Explanation: A notification must be accompanied by synchronization semantics that make earlier writes visible to the reader. Depending on the interface, a mutex, condition variable protocol, atomic operation, or join can establish the required ordering.
Q22. A thread library provides thread-specific data. A worker needs a temporary error code that must not be overwritten by other workers. Why is this facility suitable?
📖 Explanation: Thread-specific data provides a distinct instance of a value for each thread. This prevents one worker's temporary error code from overwriting another's, although genuinely shared data still requires appropriate synchronization.
Q23. A library supports a barrier for four worker threads. One worker exits before reaching the barrier, while the other three arrive. What may happen?
📖 Explanation: A barrier normally releases participants only after the required number have arrived. If one worker exits early, the others may remain blocked; robust programs need a defined failure, cancellation, or barrier-abort strategy.
Q24. A developer wants the same thread-management code to work across several operating systems. Which design choice best supports portability?
📖 Explanation: Thread libraries differ in function names, supported attributes, and detailed semantics. Using a broadly supported standard interface and isolating platform-specific extensions reduces portability problems, while still requiring checks for implementation differences.
Q25. Which statement about the implementation of a thread library is most accurate?
📖 Explanation: A thread library defines interfaces, but its implementation can use user-space code, kernel-supported operations, or both. The API abstraction therefore does not by itself reveal where every creation, scheduling, or synchronization operation executes.
Q26. A program creates two workers to sum separate halves of an array containing 20,000 values. Each worker processes 10,000 values, and the main thread needs both partial sums before displaying the total. What should it do?
📖 Explanation: Each worker must finish its assigned 10,000 elements before its partial sum is final. The main thread should wait for both completions, then combine the results; joining provides a direct way to establish that completion point.
Q27. A program creates four workers to process equal portions of an array. Each worker requires 5 ms, and the main thread performs an independent 3 ms calculation before joining all workers. Ignoring overhead, what is the earliest completion time?
📖 Explanation: The four workers execute concurrently and finish after 5 ms. The main thread's independent 3 ms calculation overlaps their work, so joining completes at 5 ms rather than adding the durations to obtain 8 or 23 ms.
Q28. A library provides an initialization function for a thread-attribute object. What is the main reason to initialize such an object before setting attributes?
📖 Explanation: An attribute initialization operation prepares the library's attribute object for use. The program can then set supported properties, such as stack or scheduling attributes, and pass the configured object to thread creation.
Q29. A worker encounters a recoverable task error in a program that processes many independent jobs. What is the strongest library-level design approach?
📖 Explanation: A recoverable task failure should be communicated without corrupting shared state. The worker may continue or be replaced according to the error, allowing unrelated tasks to proceed instead of unnecessarily terminating the entire process.
Q30. A student says that using a thread library makes synchronization unnecessary on a multicore processor. Which correction is most accurate?
📖 Explanation: A thread library supplies synchronization tools but does not automatically apply them to application data. Multiple cores can execute conflicting accesses simultaneously, so programmers must protect shared invariants with suitable locks or atomic operations.
Q31. A thread library supports a stack-size attribute. A worker has deep recursion and large local arrays. What is the risk of choosing a stack that is too small?
📖 Explanation: Recursive calls and large local objects consume stack space. If the configured stack cannot accommodate the worker's maximum usage, it may overflow and fail, so the size must reflect realistic call depth and local storage needs.
Q32. A benchmark records worker count and cumulative thread-creation time: (1,0.2 ms) ; (2,0.4 ms) ; (3,0.6 ms) ; (4,0.8 ms) ; (5,1.0 ms). Which conclusion is supported?
📖 Explanation: The measurements increase by 0.2 ms whenever one worker is added. This describes the benchmark's observed cumulative creation cost, not a universal timing guarantee for every thread library or operating system.
Q33. A developer assumes that a join operation creates a new thread to collect another thread's result. What is the correct interpretation?
📖 Explanation: A join operation coordinates with an existing thread and waits for its termination. It does not create a new execution entity, duplicate the target, or restart its computation; it provides a completion synchronization point.