Race conditions

1 Aug

Race conditions came up during a conversation I had about a week ago. I tried to explain them as best I could, but I failed horribly, metaphor piled on top of metaphor, I just couldn’t come up with a simple explanation.

A much clearer metaphor came to me today, so here goes:

I ask Charile to drive to the store. 
At the same time I ask Sally to go along and pick up something from the store. 

And just like that we’ve created a race condition. Sally getting to the store depends on her riding with Charile. I never told Charile to wait on Sally, so Charile gets in his car and drives away, leaving Sally stuck with no way to complete her task. 

Now Charile is usually slow getting ready, and thus slow to get to his car. This means Sally is usually there waiting on him. But every now and then, Charile has is keys in hand, ready and waiting.

So often Sally will make it to the store, but every so often she won’t and the system falls apart.

This is the most basic race condition. Two tasks (one driving, one riding) where one depends on the other, and it can be fixed simply enough. We just need to tell Charile to wait until Sally is ready, and then drive to the store.

I’d be interested to hear other people’s non-CS explanations for problems like race conditions, deadlocks, memory management, etc.