Search code examples
c++lock-free

convert if/assign to thread-safe CAS operation


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?


Solution

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