A paper I wrote on locking several years ago. I reproduce it here in parts.
Elements of locking
In this paper we discuss the various aspects of locking, including designing code which would be considered safe. By safe, we mean free of unexpected side effects. These side effects are commonly known as race conditions in the literature of operating systems and computer architecture. Although a lot has been written on this subject, we will look at it from a different angle. Several examples have been used to illustrate the contents of this paper, the reader is not expected to understand the code listings and what the code does. The code should be viewed from the point of view of locking. The term locking has been used here to mean methods of protecting critical section of the code. It is assumed that the reader is familiar to some extent with the concept of critical section. Most of the examples and treatment of this subject is with respect to a operating system kernel concept, but the principles discussed here even apply to a multi-process or a multi-threaded user application. All the discussion applies to non-preemptive kernels only.