int TestAndSet(int *ptr, intnew) {
int old = *ptr;
*ptr = new;
return old;
}
I am confused about why the TestAndSet can avoid two threads get the mutex.
Supposing thread A executes TestAndSet first and arrives at 'int old = *ptr'; Meanwhile, thread B executes the 'int old = *ptr' before thread A executes '*ptr = new'. In that case, the two threads get the same return value and can both get mutex.
So, what's wrong with my thought?
Yeah, and infinite loops (without side-effects) are UB...
But I guess it's just pseudocode. TestAndSet would have to be an atomic operation for this to work.
Wikipedia wrote:
the function must execute atomically. That is, no other process must be able to interrupt the function mid-execution, thereby seeing a state that only exists while the function executes. That requires hardware support; it cannot be implemented as shown.