A simple way to avoid the critical section problem is by implementing a flag that can be tested and updated atomically. A Mutex is basically a flag. Mutex means mutual exclusion and has two states, either 1 or 0.
A mutex should be created for every shared resource whose critical section accesses want to be controlled. Whichever critical section that wants to gain access over this resource need to check the mutex flag first. If the mutex is 0 it must first swap the flag value and then access the resource. If the mutex is one, it should wait until the resource is free (the flag is 0).