What is a race condition and how do you prevent it?
✅ Answer:
A race condition occurs when multiple threads access and modify shared data concurrently, and the final result depends on the timing of their execution. This can lead to inconsistent or unpredictable behavior.
To prevent race conditions, I typically use synchronization mechanisms such as mutexes, locks, or semaphores to ensure only one thread modifies critical sections at a time. In some cases, I prefer immutable data structures or atomic operations to reduce locking overhead. The choice depends on the performance requirements and contention level.