If I have a critical section, I must implement a method for locking it. I saw the following option:
while(lock) { //do nothing } lock = true; // code of critical section lock = false;
Nevertheless, I'm suspicious of it, because theoretically multiple threads can perform while(lock)(and check to see that it = false), and enter the critical section together, because while(lock)and lock = true;not performed in one continuous block. Am I mistaken? Or is this really not a safe method?
while(lock)
lock = true;
" ", . , , - , - lock == false . , - , .
lock == false
, , , , , (, -, ), "sorta" ...
- . , .
: , , . , . - :
// note: incomplete, not reentrant, not intended for real use atomic_type spin_lock = 0; // enter the spin lock: int prev_value; while ((prev_value = test_and_set(&spin_lock, 1)) != 0 || spin_lock != 1) ; // code of critical section // release the spin lock: test_and_set(&spin_lock, 0);
, . , " " "" .
What you are trying to implement is called spinlock. The new C11 standard C11 implements a primitive data type called atomic_flagthat can be used like this. Almost all modern hardware supports it, but, unfortunately, most compilers still do not support it at the syntax level, but have their own extensions. For example, gcc has built-in __sync_lock_test_and_setand __sync_lock_releasefor this.
atomic_flag
__sync_lock_test_and_set
__sync_lock_release