I was planning to post about the context and assumptions of this blog, but I realized that a page is a better format as I anticipate it will need completion and amendments.
Today, we will go through the 101 on multithreading issues.
The first ones every developer is bound to encounter are race conditions.
It covers all cases where two (or more) threads are competing for a variable (or object, or any resource for that matter): as threads are ruthless this often ends in a gory way.
Let’s use Scrabble as an analogy: a player first identify a word fitting the current game, then he put the required letters. Finally he picks as many letters he as used.
The normal rule is that players play one after the other. But suppose we remove that rule and that now players plays simultaneously. There will be of course a situation the word a player as selected is now longer fitting the game because of some other players action. And if two players are laying letters in the same area at the same time, it will get really messy, we can probably assume that those players would start to argue, and the game would be over, leaving a board with both meaningful and nonsense words on it.
That perfectly describes a race condition: the players represent the various threads and the board represents the application memory, players argument is an exception which leads to program termination.
Well, of course, actual players would find out fast that something is not right, but race conditions in a program may take some time to surface. The reason is simple, an actual scrabble board is 525 cells and a human will take several seconds to lay down a word of five to seven letters, while a computer program needs fraction of a milliseconds to modify a hundred bytes within a multimegabytes space!
What does it mean for the user of the system: that sometimes the application behaves strangely, displaying inconsistent data, garbage or simply crashes.
For the developer, it just means that he is entering a world of pain trying to chase the bug, because race conditions are as difficult to chase than the dreaded memory bugs, possibly more.
This is something that must be avoided at all costs, as no tolerance mechanism can be implemented against this. You need to be scared to death of race conditions.
I did face my share, directly or indirectly, most of them dragged on for weeks or months, usually until the code is significantly refactored.
Next post will talk about the traditional solution to race conditions, namely locks. It wil give us also the opportunity to talk about deadlock.
One thought on “Multithreading issues 1: race conditions”
Thank you for beeing you