How do we fix the preceding race? It's quite straightforward, really: we have to ensure that, as stated earlier, the banking operations—deposits, withdrawals, and so on—are guaranteed to do two things:
- Be the only thread running the code at that point in time
- Be atomic — run to completion, without interruption
Once this is achieved, the shared data will be safe from corruption. The section of code that must run in the fashion described previously is called a critical section.
In our fictional banking application, the threads running the code to perform a banking operation (a deposit or a withdrawal) must do so in a critical section, shown as follows:
So, now, let's say that the banking application ...