Search code examples
clockingcritical-section

Is polling for a lock a correct way to implement critical sections?


If I have a critical section, I must implement a method of locking it. I saw the following variant:

while(lock)
{
    //do nothing
}
lock = true;
// code of critical section
lock = false;

However, I'm suspicious about it because in theory, several threads can perform while(lock) (check and see that it's = false), and get into critical section together because while(lock) and lock = true; are performed not in one continuous block. Am I wrong? Or this is indeed a not safe method?


Solution

  • This is "almost safe", i.e. not safe at all. What it's lacking is exactly what you are seeing - multiple threads could see lock == false and enter the critical section. It needs an atomic operation, which must be supported by the hardware - a way to guarantee that only one thread of execution can acquire the lock.

    That said, if the system you're writing can survive mutual exclusion failure, and be ok with working usually with occasional failures (perhaps logging or something where the occasional mangled entry wouldn't necessarily cause total failure), this pattern could "sorta" work...