gpt4 book ai didi

c++ - 将 if/assign 转换为线程安全的 CAS 操作

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:11 26 4
gpt4 key购买 nike

我在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com