📝 Thread local storage TLS in operating system (33 MCQs)
Private Per-Thread Data Within a Shared Process
Thread-local storage (TLS) provides variables that appear private to individual threads even though those threads share one process address space. It belongs to thread management and runtime memory organisation, allowing each thread to maintain independent values without requiring every function to pass those values explicitly. The operating system, compiler, and runtime cooperate to provide suitable thread-specific storage mechanisms.
Why Shared Global Variables Are Unsuitable for All Thread Data
Ordinary global variables are accessible to every thread in a process, so concurrent updates may interfere with thread-specific calculations or execution state. Protecting every such value with locks increases complexity and overhead. TLS addresses this problem by providing separate instances of selected variables for each thread, reducing unnecessary sharing and simplifying some concurrent programming patterns.
Thread-Specific Variable Allocation and Access
When a thread accesses a TLS variable, the compiler and runtime resolve the reference to that thread's own storage instance. Each thread maintains a distinct value, while code can use the variable through an ordinary source-level identifier or a thread-specific data API. The storage remains associated with the thread and is managed according to the language and runtime rules.
Maintaining Independent Error Values in Two Threads
Suppose thread T1 encounters an error and stores error value 5 in a thread-local variable. Thread T2 independently encounters another error and stores value 12 in the same declared TLS variable. T1 reads 5 and T2 reads 12 because each accesses its own storage instance rather than overwriting the other thread's value.
Thread Isolation, Storage Overhead, and Lifetime
TLS is useful for per-thread error information, library state, temporary buffers, and runtime bookkeeping. It reduces the need for locks when data is genuinely thread-specific. However, TLS does not protect shared objects or eliminate synchronisation requirements. Large TLS allocations and complex thread lifetimes can increase memory use, while access and destruction behaviour depends on the implementation.
Misconceptions About Thread-Local Variables
'TLS creates a separate process address space for each thread' is incorrect because threads still share the process address space. 'Thread-local variables are visible with identical values to all threads' is incorrect because each thread has its own instance. 'TLS eliminates every race condition' is incorrect because shared data remains vulnerable to unsynchronised access.
Exam Focus: Distinguishing Shared and Thread-Local Data
Determine which variables are shared and which have independent per-thread instances. Trace assignments by two threads and identify why their TLS values do not overwrite each other. Questions may compare TLS with global variables, stack variables, mutex-protected state, and process-local data, or examine storage overhead and thread lifetime.
Key Terms of Thread-Local Storage
- TLS - Storage maintained separately for each thread.
- Thread-specific data - Values associated with one thread.
- Global variable - Process-wide shared variable.
- Thread lifetime - Period during which a thread exists.
- Storage instance - Individual allocation for a thread.
- Runtime - Software managing execution and storage.
📝 All Thread local storage TLS in operating system MCQs
Q1. A multithreaded web server runs the same request-handling function on many workers. Each worker needs a private request identifier that remains available to helper functions without being passed as an argument. Which storage choice fits best?
📖 Explanation: TLS gives each worker thread its own instance of the request identifier, while helper functions running on that thread can access it. The threads continue sharing the process address space and unrelated global objects.
Q2. Threads A and B each begin with a TLS integer named count equal to zero. A increments its instance four times, and B increments its instance seven times. What values do they read afterward?
📖 Explanation: Each thread updates its own instance, so A's four increments affect only A's count and B's seven increments affect only B's count. The shared declaration does not make their stored values shared.
Q3. A database client library keeps the current transaction label in an ordinary global variable. Several threads call the library concurrently, each requiring a different label. Why is replacing that variable with TLS a suitable design?
📖 Explanation: A TLS label is independent for each calling thread, so one transaction does not overwrite another thread's label. Unlike process isolation, TLS changes the storage instance, not the process address space or ownership of other data.
Q4. A graph plots each thread's TLS counter after successive updates. Thread A has points (0,0), (1,2), (2,4), (3,6), (4,8); Thread B has points (0,0), (1,3), (2,6), (3,9), (4,12). Which interpretation best fits the traces?
📖 Explanation: The two traces progress independently: A increases by two per update, while B increases by three. Separate TLS instances explain both sequences without requiring one thread's writes to replace the other's stored counter.
Q5. A student argues that TLS works because every thread receives a separate virtual address space, so no thread can access another thread's memory. Which correction identifies the flawed reasoning?
📖 Explanation: The student's error is treating TLS as process isolation. Threads in one process share an address space; TLS supplies thread-associated instances of particular variables, while ordinary shared objects remain accessible under normal memory and synchronization rules.
Q6. A function is called repeatedly by the same worker thread. It declares one ordinary automatic local variable and also accesses a TLS variable. Which behavior normally distinguishes the two?
📖 Explanation: An ordinary automatic local has a lifetime tied to its function invocation. A TLS instance is associated with the thread, so its value can remain available across calls until changed or the thread's applicable storage lifetime ends.
Q7. A function stores an intermediate result in TLS and calls a callback on the same thread. The callback uses the same TLS variable for its own intermediate result. What must the outer function do if it still needs its original value afterward?
📖 Explanation: TLS separates threads, not nested calls within one thread. Both functions reach the same thread's instance of that variable, so the callback can overwrite the outer value unless the design preserves or separates the state.
Q8. A reentrant formatter uses a TLS scratch buffer. While formatting an outer message, it invokes a callback that formats an inner message using the same buffer. The outer formatter then resumes. What is the central risk?
📖 Explanation: The buffer is private from other threads but is not private from nested operations on its owning thread. The inner formatter can replace its contents, so reentrant code should use separate buffers or save and restore state.
Q9. A student says, 'A variable declared inside a function is automatically TLS because each thread has its own stack.' Which part of this reasoning is incorrect?
📖 Explanation: The flawed step is equating a thread's stack with TLS. Ordinary automatic locals belong to individual invocations, whereas TLS has thread storage duration and can be accessed across different calls on the same thread.
Q10. In a C++ program, a thread-local integer is initialized to 3. Thread A changes its instance to 9 before Thread B first uses its instance. Under the language's per-thread initialization model, what should B observe on first use?
📖 Explanation: Each thread has a distinct thread-local object, initialized according to the variable's initialization rules for that thread. A's assignment changes only A's instance, so B does not inherit the value nine.
Q11. A server reuses each worker thread for many customer requests. One request stores customer ID 481 in a TLS variable, and the next request handled by the same worker reads that variable before assigning its own ID. What is the likely defect?
📖 Explanation: TLS follows the worker thread's lifetime rather than the lifetime of an individual request. A reused worker can retain the previous request's value, so request setup and completion must manage the thread-local state explicitly.
Q12. A program stores a pointer to a malloc-allocated scratch area in a TLS slot. The owning thread terminates, and the program has installed no destructor or other cleanup routine. What resource-management problem can result?
📖 Explanation: TLS controls the lifetime of the pointer variable or slot, not automatically the lifetime of a heap object it references. Without explicit cleanup or a runtime destructor, the allocation may remain unreleased after thread termination.
Q13. A POSIX program allocates one dynamic buffer per thread and stores its pointer with pthread_setspecific(). Which mechanism is designed to release each non-null buffer when its owning thread exits?
📖 Explanation: A destructor supplied when creating a POSIX thread-specific-data key is invoked for a thread's non-null associated value at thread termination. The destructor can release that thread's buffer, avoiding reliance on another thread's TLS instance.
Q14. An authentication service uses a TLS variable for the current user's access token. Worker threads process multiple unrelated users sequentially. Which practice best prevents one user's token from affecting a later task on the same worker?
📖 Explanation: A worker's TLS instance can outlive an individual task. Clearing the token when a task completes prevents later work on that same thread from accidentally inheriting stale credentials, including when cleanup handles exceptional exits.
Q15. Threads A and B have distinct TLS pointer variables. Both pointers are assigned the address of the same mutable heap object. Which statement is correct?
📖 Explanation: TLS provides separate storage for the pointer variables, not automatic copies of their targets. Because both pointers identify one heap object, either thread can affect the same mutable state and synchronization may be necessary.
Q16. Each database worker stores its own transaction context in TLS, but every context references one mutable connection pool shared by the process. A race occurs while workers acquire and return connections. What is the best diagnosis?
📖 Explanation: The transaction-context variables are per-thread, but the referenced connection pool remains shared. TLS does not synchronize operations on that pool, so its internal state needs locks, atomic operations, or another concurrency-safe protocol.
Q17. A student sees two threads with different TLS pointer values and concludes that the objects must also be independent. Both pointers actually contain address 0x5000. Which step in the student's reasoning is faulty?
📖 Explanation: The faulty step is extending variable isolation to the referenced allocation. The two TLS pointer slots are separate, but the identical address 0x5000 identifies one shared object whose concurrent modification still requires coordination.
Q18. A library returns a pointer to a TLS scratch buffer. A caller saves that pointer, calls the library again on the same thread, and then reads the saved pointer. What should the caller anticipate?
📖 Explanation: Repeated calls on one thread commonly reuse that thread's instance of the TLS buffer. A later call may overwrite the earlier contents, so callers needing a persistent result should copy it or use separately owned storage.
Q19. A simulation runs many threads, each collecting an independent count of events. The application only needs the combined total once per minute. Which design most directly uses TLS to reduce synchronization overhead?
📖 Explanation: Independent counters do not need to contend on one shared variable during every event. TLS permits local increments, while a deliberate periodic aggregation step combines the results and handles publication consistently.
Q20. A memory-usage graph plots the total storage for a 64-byte TLS variable across threads: (1,64), (2,128), (4,256), (8,512), (16,1024). According to the plotted pattern, how much storage is used by eight threads, excluding alignment overhead?
📖 Explanation: The plotted storage grows by 64 bytes per thread. For eight threads, the total is bytes, matching the point (8,512); alignment and implementation metadata are explicitly excluded.
Q21. A monitoring system requires an exact process-wide event total to be visible immediately after every increment. Each worker currently increments only its own TLS counter, while a collector reads and sums counters every five seconds. What change is needed to meet the requirement?
📖 Explanation: Periodic aggregation produces a delayed snapshot, not an immediately current total. The requirement needs coordinated publication on each update, such as an atomic shared counter, accepting the synchronization and contention costs of global visibility.
Q22. Which workload is the strongest fit for TLS rather than one mutex-protected global variable?
📖 Explanation: TLS is most useful when values are genuinely private to each thread and do not require immediate global visibility. Independent parsing statistics can be accumulated locally and combined later without locking every update.
Q23. A web server moves a per-thread lookup cache into TLS, but cache misses still contend. Profiling shows that each miss inserts an entry into one shared hash table. Which conclusion best links the two mechanisms?
📖 Explanation: The local cache can be thread-specific while the hash table remains a shared mutable object. Concurrent misses still reach that common structure, so its insertion path must provide its own synchronization or concurrency-safe design.
Q24. A Windows program needs a process-wide TLS index that each thread can use to access its own slot. Which function allocates that index?
📖 Explanation: TlsAlloc reserves a TLS index for use by threads in the process. Each thread then has a separate slot associated with that index, initially set to NULL, and can store or retrieve its own value.
Q25. A Windows worker stores a pointer in its slot for index k, then later retrieves it using the same index. Which API sequence expresses these operations for the calling thread?
📖 Explanation: TlsSetValue stores a value in the calling thread's slot for the specified index, and TlsGetValue retrieves that slot's value. Another thread using the same index accesses its own corresponding slot.
Q26. A POSIX program creates one thread-specific-data key and then lets several threads store different context pointers using that key. Which statement describes the key and values correctly?
📖 Explanation: A POSIX key identifies a thread-specific slot common to the process's threads. pthread_setspecific changes the calling thread's association, and pthread_getspecific reads that same thread's value for the key, not another worker's stored value.
Q27. A student claims that all POSIX threads read the same value because they pass the same pthread_key_t to pthread_getspecific(). What is wrong with the claim?
📖 Explanation: The mistaken step is equating a common key with a common value. POSIX thread-specific data associates a separate value with that key in each thread, so retrieval returns the calling thread's association.
Q28. A POSIX program creates key K with a destructor, stores a non-null buffer pointer for Thread A, and leaves Thread B's value for K as NULL. Later, both threads exit and the program calls pthread_key_delete(K). Which statement is accurate?
📖 Explanation: A POSIX key destructor is called at thread termination for that thread's non-null associated value. A NULL value triggers no destructor, and pthread_key_delete deallocates the key without calling its destructor for existing values.
Q29. A reporting graph lists published TLS counters at one consistent snapshot: Worker 1 = 4, Worker 2 = 7, Worker 3 = 2, Worker 4 = 5, Worker 5 = 6. What total should the reporting routine calculate from these published values?
📖 Explanation: The reporter must aggregate the five published worker values: . Reading only the reporter's own TLS instance would not produce this process-wide total.
Q30. A monitoring thread calls pthread_getspecific() with a valid key used by all workers. Which value does the call return?
📖 Explanation: pthread_getspecific retrieves the value associated with the key for the calling thread. Sharing the key does not let a monitoring thread inspect other threads' private values or automatically calculate an aggregate.
Q31. A monitor reads its own TLS variable named completed_requests, obtains zero, and reports that no worker has completed a request. What is the error in this conclusion?
📖 Explanation: The flawed step is treating the monitor's thread-local value as a process-wide statistic. Its read concerns only its own instance; workers must publish their counts through a shared reporting structure or explicit collection mechanism.
Q32. A service stores a private cache descriptor in each thread's TLS, but all descriptors reference one mutable eviction queue shared by the service. Which design best preserves correctness under concurrent cache misses?
📖 Explanation: The descriptors are per-thread, but their common eviction queue is still shared mutable state. Correctness requires synchronization or a concurrent queue design around shared operations; TLS alone protects neither the queue nor its invariants.
Q33. A user-level task stores its current transaction context in TLS, is suspended, and later resumes on a different operating-system worker thread. The resumed task reads a different context. What design change addresses the underlying mismatch?
📖 Explanation: TLS follows the operating-system thread, not a migratable logical task. When a task resumes on another worker, it sees that worker's instance; task-specific context should travel with the task or be restored explicitly.