Reputation: 210
I am trying to implement Test and Test-and-set in c++.
as per C++ atomic_flag query state we cannot check the flag state, so whats the workaround for that
loop will be like this
std::atomic_flag lock_stream = ATOMIC_FLAG_INIT;
void ttas_lock()
{
while(lock_Stream);
while(lock_stream.test_and_set());
return
}
error: could not convert ‘((ttas*)this)->ttas::lock_stream’ from ‘std::atomic_flag’ to ‘bool’ while(lock_stream)
Upvotes: 5
Views: 10669
Reputation: 12335
If you want to test lock_stream without setting it, you should use std::atomic<bool>
.
Therefore, declare it as:
std::atomic<bool> lock_stream = ATOMIC_FLAG_INIT;
Instead of test and set, you just use exchange:
void ttas_lock()
{
while(lock_stream);
while(lock_stream.exchange(true)); // this is equivalent to test and set
return;
}
According to wikipedia, if test and set fails, you should do the test again, which results in:
void ttas_lock()
{
do {
while (lock_stream) continue;
} while (lock_stream.exchange(true)); // actual atomic locking
return;
}
Upvotes: 2
Reputation: 27567
Your function:
void ttas_lock()
{
while(lock_Stream);
if(!lock_stream.test_and_set()) return;
}
will always return
after lock_Stream
is false
. Not what you want.
Upvotes: 0