Codele / Advanced programming
Race conditions and locks
Two workers who change the same thing at the same moment can undo each other’s work. A lock lets only one worker in at a time.
- A race condition is a bug where the result depends on which worker happens to be quicker. Reading a number, adding 1 and writing it back is three separate moves, and another worker can slip in between them.
- Each worker keeps a private copy of what it read. If both read 5, both write 6, and one add is lost.
- A lock lets only one worker hold the key at a time, so read-add-write becomes one unbroken block. Real languages have it built in: Python threading.Lock, Java synchronized or ReentrantLock, C# lock, C++ std::mutex, Go sync.Mutex. JavaScript in one thread rarely needs one.
- A deadlock happens when two workers each hold one lock and wait for the other’s. Neither can move. Take locks in the same order everywhere, and keep the locked part small.
- This lesson fixes the turn order on purpose so it prints the same every time. Real threads race unpredictably, which is exactly why these bugs are so hard to find.
Loading the playable lesson…