Skip to the guide

Threads, shared state and race conditions

BeginnerConcept6 pages

A thread is one line of work running through your program, and a program can run many at once. Threads share the program's objects, and a race condition is a bug where the result depends on which thread happens to go first. The interviewer wants you to name the data that is shared and changes, and to tell the bad order as a scene.

Two workers and one chalkboard

Picture a warehouse with a chalkboard by the door that shows how many boxes have gone out today. Every worker follows the same card on the wall. Read the board, write that number plus one in your own notepad, carry a box out to the truck, walk back, and copy the notepad's number onto the board. The warehouse's name is painted above the door.

One worker alone is always right. Now two start at the same moment. Ana reads 41, writes 42 in her notepad and walks out to the truck. Ben reads the board while she is outside, and it still says 41, so he writes 42 as well. Both come back and both write 42. Two boxes went out and the board went up by one, yet neither made a mistake.