A more robust alternative to simple mutexes is to use semaphores, which are integer variables for which only two atomic operations are defined: wait() and signal().
Possible implementation of wait() and signal(). Taken from Bell, John T. "Process Synchronization." University of Illinois, Chicago.
Using the Semaphores method. Taken from Bell, John T. "Process Synchronization." University of Illinois, Chicago.