我在使用 CAS 指令方面完全是新手,所以很抱歉回答这么简单的问题,但我必须了解基本的事情
那么是否可以将此代码转换为某些 CAS 指令以使该代码线程安全?
if (a == 0) {
a = 1;
return true;
} else {
return false;
}
在现实生活中,这段代码看起来像这样:
// 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;
}
}
我更喜欢可移植解决方案(可以在 Windows 和 Linux 上运行),也许我应该使用 std::atomic
?
最佳答案
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);
}
查看有关 std::atomic 的更多信息 here .
关于c++ - 将 if/assign 转换为线程安全的 CAS 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16200685/