In some cases we need to be sure that some section of code won’t be used by one thread while another thread is in this section. Using languages that support multi-threading it’s easy to achieve with “locking” these parts. But when we have to “simulate” threads there’s not built-in thing like lock keyword in C# or Lock interface in Java. The best way I’ve found to lock sections in these cases look likes this:
if (!locked){
locked = true;
do some stuff
locked = false;
} else {
add to queue
}
What are the drawbacks of current solution? Does it worth to actively use one?
Maybe two threads can enter in the
ifstatement.Explanation
If
T1entered in theifstatement and doesn’t change thelockedvalue. Suddenly, if the CPU changeT1forT2,lockedvalue will continuefalse. ThenT2will enter intoifstatement too.You should take a look at Semaphores and Mutexes and If you will only use two process you can use the Peterson’s Algorithm, but it still have a busy wait to deal!