Mutex Test and Set

I read the code about Mutex test below:
1
2
3
4
5
6
7
8
9
static int flag=0;

void lock(){
  while(TestAndSet(&flag,1)==1);
  //flag=1;
}
void unlock(){
  flag=0;
}

And TestAndSet:
1
2
3
4
5
int TestAndSet(int *ptr, int new) {
    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?
Last edited on
This doesn't seem to be valid C++. I don't believe the keyword 'new' can be used as a variable name.

I wouldn't trust this information.
Sorry for the mistake.
I just wonder how I can implement a TestAndSet function.
Thanks for your help.
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.
https://en.wikipedia.org/wiki/Test-and-set#Software_implementation_of_test-and-set
Last edited on
Thanks for your reply which makes me figure it out.
Topic archived. No new replies allowed.