Your joint account holds Tk 10,000. At three in the afternoon you stand at one ATM and your brother stands at another. You ask for Tk 2,000, he asks for Tk 3,000, and by bad luck you both press the button in the same instant. Each machine does the same three things: read the balance, subtract the amount, write the new balance back. What does the account show afterwards? Tk 5,000, if the bank is careful. If it is not, the account may show Tk 8,000 or Tk 7,000, and one of the two withdrawals has simply vanished from the books. Real banks are not that careless, and the reason they are not is the subject of this chapter.
The same trap sits inside every computer. A modern machine runs dozens of processes and threads at once, and many of them touch the same variables, the same files and the same tables. When two of them update one thing at the same time, the result depends on who happened to be first, and that is a bug you cannot reproduce on demand. The cure is to make them take turns, and the art of taking turns correctly is called synchronization.
By the end of this chapter you will be able to show how an innocent count++ loses updates, and to state the critical-section problem with its three requirements. You will explain Peterson's solution and why it breaks if two of its lines are swapped, build a lock from test-and-set and from compare-and-swap, and say when a spinlock is the right lock. You will trace a semaphore by hand and use one as a lock, as a count of resources and as a way to put two actions in order. You will tell a mutex from a semaphore, explain priority inversion and its cure, and explain what a monitor and a condition variable do and why a waiting thread re-tests its condition in a loop.