Which of the following is/are correct for implementing thread safety in a multi-threaded...
Micron technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Which of the following is/are correct for implementing thread safety in a multi-threaded program?
(i) Allocating separate private stack to each thread in the program so that all processes can be utilized
(ii) Allocating not more than one thread to read the shared data at a time
(iii) Using atomic operations with shared data
Show answer & explanation
Thread safety requires mutual exclusion when accessing shared data. Statement (ii) is correct—limiting concurrent access to one thread prevents race conditions. Statement (i) is incorrect—separate stacks are already allocated per thread by default and don't directly implement thread safety. Statement (iii) is misleading in isolation—atomic operations alone are insufficient; read-only access to shared data must also be protected from concurrent writes.
Step-by-step Derivation:
Analysis of each statement:
(i) Separate private stacks per thread: This is already done by default in multi-threaded systems. Each thread gets its own stack for local variables. However, this alone does NOT ensure thread safety—the problem occurs when threads access shared (heap) data simultaneously. Separate stacks are a prerequisite but not a thread-safety mechanism. ✗
(ii) Not more than one thread reading shared data at a time: This is a mutual exclusion principle—the core of thread safety. By serializing access (only one thread at a time), race conditions are prevented. This is a valid thread-safety technique using locks/mutexes. ✓
(iii) Using atomic operations with shared data: While atomic operations prevent torn reads and ensure visibility, they don't guarantee correctness for complex operations. Atomic operations alone cannot enforce the read-modify-write atomicity needed for most shared data scenarios. Moreover, read-only access to shared data doesn't require atomics if writes are properly synchronized. Partial correctness at best. ✗
Conclusion: Only (ii) correctly describes a fundamental thread-safety mechanism.