Write a multi-threaded C++ program
Filed under Morgan Stanley
Free read 3 of 3Threads share the process's heap, global variables, and data segments, but maintain their own stack and registers.
The question
Write a multi-threaded C++ program and discuss shared memory, concurrency issues, locking mechanisms, lock pitfalls, and deadlock prevention.
Constraints
- Language: C++ (using std::thread, std::mutex, etc.)
Approach
Threads share the process's heap, global variables, and data segments, but maintain their own stack and registers.
Race conditions occur when multiple threads access shared data concurrently without proper synchronization.
Use std::mutex, std::lock_guard, or std::unique_lock to protect critical sections and ensure mutual exclusion.
Prevent deadlocks by establishing a global lock acquisition order, using std::lock for multiple mutexes, or implementing timeout mechanisms.
Tips
- What they are testing: Test multi-threaded code under high concurrency to expose race conditions.
- Common mistake: Forgetting to lock shared resources or acquiring locks in inconsistent orders leading to deadlocks.
Related Morgan Stanley questions
Collected from public candidate posts and coding forums. Updated Nov 2026.