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?

有帮助吗?

解决方案

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.

其他提示

That is exactly what CAS is doing, yes. C++11 has std::atomic and its compare_exchange_weak and compare_exchange_strong for that.

you do

std::atomic<int> a;

int expected = 0;
return a.compare_exchange_strong(expected, 1);

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."

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top