← WeRide Interview InsightsSoftware Engineer
The race condition part was fine, i knew the answer conceptually.
Start by explaining why i++ is not atomic (read-modify-write) and demonstrate a data race with a simple multithreaded program that increments a shared counter, showing the incorrect result. Then present a thread-safe version using synchronization primitives (e.g., mutex, atomic operations) and discuss trade-offs.
Pro tip: Mention that even though i++ looks like a single operation, it compiles to multiple instructions, and that using atomic operations can be more efficient than locks for simple increments. Also, note that the demonstration should include a way to reliably reproduce the race, such as using many iterations and threads.
Describe that i++ involves three steps: read the current value, increment it, and write it back. In a multithreaded context, these steps can interleave, leading to lost updates.
Create a simple program (e.g., in C++ or Java) with multiple threads incrementing a shared variable many times. Run it and show that the final value is often less than expected due to the race.
Point out that without synchronization, threads may read the same value simultaneously, and one thread's write can overwrite another's, causing lost increments.
Modify the program to use synchronization: either a mutex/lock around the increment, or an atomic variable (e.g., std::atomic in C++). Show that the final value is now correct.
Compare performance and complexity of locks vs. atomics. Mention that atomics are typically faster for simple operations but may not be suitable for complex critical sections.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.