我在使用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
发布于 2013-04-25 03:40:27
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的信息。
发布于 2013-04-25 03:36:56
这正是CAS正在做的事情,是的。C++11为此提供了std::atomic及其compare_exchange_weak和compare_exchange_strong。
发布于 2013-04-25 03:40:02
你做了
std::atomic<int> a;
int expected = 0;
return a.compare_exchange_strong(expected, 1);https://stackoverflow.com/questions/16200685
复制相似问题