Reputation: 24067
I'm completely novice in using CAS instructions so I'm sorry for answering such simple question but I have to understand basic things
So if is it possible to convert this code to some CAS instruction to make this code thread safe?
if (a == 0) {
a = 1;
return true;
} else {
return false;
}
In real life this code looks like that:
// 0 - available, 1 - processing, 2 - ready
uint16_t status[QUEUE_LENGTH];
bool MsgQueue::Lock(uint32_t msgSeqNum)
{
if (status[msgSeqNum] == 0) {
status[msgSeqNum] = 1;
return true;
} else {
return false;
}
}
I would prefer portable solutions (that can work on both Windows and Linux), probably I should use std::atomic
?
Upvotes: 2
Views: 127
Reputation: 14471
If you're using gcc then perhaps you want __sync_val_compare_and_swap
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)
"These builtins perform an atomic compare and swap. That is, if the current value of *ptr is oldval, then write newval into *ptr."
Upvotes: 0
Reputation: 28188
std::atomic<uint16_t> status[QUEUE_LENGTH];
bool MsgQueue::Lock(uint32_t msgSeqNum)
{
uint16_t expected = 0;
return status[msgSeqNum].compare_exchange_strong(expected, 1);
}
See more about std::atomic here.
Upvotes: 2
Reputation: 9278
you do
std::atomic<int> a;
int expected = 0;
return a.compare_exchange_strong(expected, 1);
Upvotes: 0
Reputation: 8774
That is exactly what CAS is doing, yes. C++11 has std::atomic
and its compare_exchange_weak
and compare_exchange_strong
for that.
Upvotes: 2