🎓 BookMCQ
← Back to 4. Threads in Operating System

📝 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.
11
Easy
11
Medium
11
Hard

📝 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?

A.A single ordinary global variable shared by every worker
B.A thread-local variable with a separate instance for each worker thread ✅
C.One constant stored in the executable and changed for each request
D.A single heap object that every worker updates without coordination
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.Both read eleven because they use the same variable name
B.A reads seven and B reads four
C.Both read four because A started first
D.A reads four and B reads seven ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.It gives each thread an independent label without making the entire process address space private ✅
B.It forces all transaction calls to execute one at a time
C.It creates a separate operating-system process for every transaction
D.It makes the transaction label immutable after initialization
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.The threads alternate updates to one shared counter
B.Thread B's values overwrite Thread A's values
C.Each trace represents a distinct per-thread counter instance ✅
D.TLS prevents both threads from updating counters concurrently
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.TLS creates one separate process for every thread, but shares executable code
B.Threads still share the process address space; TLS provides distinct instances of selected variables within that shared address space ✅
C.TLS works only when threads use different physical processors
D.Each TLS variable is copied into a separate file for each thread
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.Both variables are recreated with fresh storage on every function call
B.The automatic variable persists until thread exit, while TLS ends when the function returns
C.The automatic variable is shared by every thread, while TLS is process-wide
D.The automatic variable belongs to that invocation, while the TLS instance can retain its value across calls by the same thread ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.Save the value and restore it when appropriate, or use a separate state object ✅
B.Rely on TLS to create a new instance for every nested function call
C.Move the callback to another process automatically
D.Assume the callback can only read, not modify, the TLS instance
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.The callback receives a separate TLS instance because it is a different function
B.TLS automatically saves the outer buffer before every callback
C.The inner formatting operation can overwrite data that the outer operation still expects in the same thread's buffer ✅
D.The buffer becomes shared with every other process during the callback
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.A function can never access a TLS variable
B.The student confuses invocation-specific automatic storage with a variable explicitly associated with a thread; a separate stack does not convert every local into TLS ✅
C.All function-local variables are global unless protected by a mutex
D.TLS variables must be allocated on the process heap
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.Nine, because the most recent assignment initializes every instance
B.Zero, because TLS instances are cleared whenever another thread writes
C.An unspecified copy of A's current value
D.Three, because B has its own instance initialized independently ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.TLS automatically creates a fresh instance at every request boundary
B.The variable must have been stored in another process
C.The second request cannot access the worker's TLS
D.The second request may observe stale per-thread state unless the application resets or replaces it ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.The TLS slot becomes a global pointer automatically
B.The allocation is guaranteed to be freed when the pointer variable disappears
C.The heap allocation can leak because ending the TLS slot does not by itself free the pointed-to allocation ✅
D.The memory is copied to every remaining thread
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.Associate a destructor function with the key using pthread_key_create() ✅
B.Call pthread_getspecific() from an unrelated thread after every allocation
C.Use pthread_key_delete() as a command that frees every thread's pointed-to object
D.Store the pointer in a global variable and overwrite it at shutdown
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.Keep the token until the worker process terminates because TLS prevents reuse
B.Clear or replace the token at task boundaries and ensure failure paths perform the same cleanup ✅
C.Copy every token into a single global variable before each task
D.Assume the runtime creates a new thread for every user request
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.The heap object is duplicated because the pointers are thread-local
B.The object becomes immutable once two TLS pointers reference it
C.The pointers must have different addresses and therefore identify different objects
D.The pointer variables are distinct, but the object they reference remains shared ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.TLS is not operating because transaction contexts should be global
B.The connection pool becomes private whenever a thread stores its pointer in TLS
C.The TLS contexts are isolated, but concurrent operations on the shared pool still need a thread-safe design ✅
D.The race proves that TLS variables cannot contain pointers
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.The student treats distinct pointer variables as proof of distinct pointees; equal target addresses show that both threads reference the same object ✅
B.The student assumes heap objects can be reached only through global variables
C.The student forgets that TLS values can contain integers
D.The student assumes each thread must use a different process identifier
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.The second call receives a fresh TLS instance because it is a separate call
B.The saved pointer may refer to the same buffer whose contents the second call has overwritten ✅
C.The first buffer is automatically moved to another thread
D.The buffer is immutable after the first return
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.Make every event update one shared counter without synchronization
B.Protect every local increment with a process-wide mutex
C.Keep a counter in each thread's TLS and aggregate the published counts periodically ✅
D.Create a separate process for each event
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.64 bytes
B.256 bytes
C.1024 bytes
D.512 bytes ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The plotted storage grows by 64 bytes per thread. For eight threads, the total is 8×64=5128 \times 64 = 512 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?

A.Keep the periodic collector unchanged because TLS automatically updates the process total
B.Use a synchronized shared total or another update-and-publication mechanism that makes each increment visible immediately ✅
C.Read the collector thread's own TLS counter twice
D.Increase each worker's TLS counter by the number of active threads
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.Each worker maintains independent parsing statistics that can be combined after a batch ✅
B.All workers must modify the same account balance and observe every update immediately
C.Every thread must update the same linked-list head
D.All requests must share one mutable transaction state
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.TLS should serialize the shared hash table automatically
B.The cache entries must actually be stored in each process's private address space
C.TLS isolates the local cache variable, but the shared hash-table insertions remain a synchronization point ✅
D.A cache miss causes every thread's TLS instance to be merged
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.TlsSetValue
B.TlsGetValue
C.TlsAlloc ✅
D.TlsFree
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.TlsSetValue(k, pointer), followed by TlsGetValue(k) ✅
B.TlsAlloc(pointer), followed by TlsFree(k)
C.TlsGetValue(k, pointer), followed by TlsSetValue(k)
D.TlsFree(k), followed by TlsAlloc(k)
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.Each thread must create a different key before it can store a value
B.The key is common to the threads, while each thread associates its own value with that key ✅
C.pthread_setspecific stores one process-wide value shared by all threads
D.pthread_getspecific retrieves the most recently stored value from any thread
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.A pthread key is valid only in the thread that created it
B.pthread_getspecific always reads the process environment instead of thread data
C.The key is shared, but the value associated with it is maintained separately for each calling thread ✅
D.pthread_setspecific copies each stored value into every other thread
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.The destructor runs for both threads because the key exists
B.pthread_key_delete invokes the destructor for every non-null value before returning
C.The destructor runs only for Thread B because NULL signals an allocation
D.Thread A's destructor is called for its non-null value at exit; Thread B has no value to destroy, and deleting the key does not invoke those destructors ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.24 ✅
B.18
C.20
D.26
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: The reporter must aggregate the five published worker values: 4+7+2+5+6=244 + 7 + 2 + 5 + 6 = 24. 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?

A.The value most recently stored by any worker
B.The value associated with that key in the monitoring thread itself ✅
C.A randomly selected worker's value
D.The sum of every thread's value for the key
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.The monitor used TLS rather than a global variable, so its own instance does not represent the workers' instances; their counts must be published or collected explicitly ✅
B.A TLS integer cannot store a request count
C.A zero value proves that all worker threads have terminated
D.TLS automatically resets every worker's counter whenever the monitor reads it
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.Remove the TLS descriptors so every operation uses an unsynchronized global pointer
B.Assume that separate descriptors guarantee separate eviction queues
C.Duplicate only the descriptor pointer whenever two threads access the queue
D.Protect the shared queue with a suitable concurrent protocol, because TLS does not isolate the object referenced by each descriptor ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.Store the context in the task's own state so it follows the task when execution moves between threads ✅
B.Increase the size of each worker's TLS block
C.Copy the first worker's entire TLS area into every process
D.Use one global context variable without synchronization
💡 Difficulty: hard | ✅ Correct: A

📖 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.

🔗 Related Topics (MCQs)