端口 pthread_cond_broadcast 到 std::atomic

Port pthread_cond_broadcast to std::atomic

试图理解 std::atomic(C++ 11 中的无锁操作)的所有内容。

我想知道是否有这样的操作:

bool SomeClass::waitMyVariableToBeSet() {
    pthread_mutex_lock(&mMutex);
    while (!MyVariableToBeSet) {
        r = pthread_cond_timedwait(&msCondVariableSet, &mMutex, &ts);
    }
    pthread_mutex_unlock(&mMutex);
}

void SomeClass::setMyVariable(bool newVal) {
    pthread_mutex_lock(&mMutex);
    MyVariableToBeSet= newVal;
    pthread_cond_broadcast(&msCondVariableSet);
    pthread_mutex_unlock(&mMutex);
}

可以这样替换成std::atomic:

std::atomic<bool> MyVariableToBeSet;

bool SomeClass::waitMyVariableToBeSet() {
    uint someTimeOutCnt = 100;
    while (!MyVariableToBeSet.compare_exchange_strong(false, true) && SomeTimeCnt) {
         someTimeCnt--;
         std::this_thread::yield(); // no sure of this here
   }
}

void SomeClass::setMyVariable(bool newVal) {
    MyVariableToBeSet= newVal;
}

C++ 20 实现了解决方案

https://en.cppreference.com/w/cpp/atomic/atomic_flag

否则,我认为自旋锁将是所有权衡取舍的折衷方案。

在 C++20 中,这可以使用新的原子 wait and notify 操作来实现:

std::atomic<bool> MyVariableToBeSet;

bool SomeClass::waitMyVariableToBeSet() {
    MyVariableToBeSet.wait(false);
}

void SomeClass::setMyVariable(bool newVal) {
    MyVariableToBeSet = newVal;
    MyVariableToBeSet.notify_all();
}

在内部,这些将使用队列的哈希映射或尽可能使用 futex, WaitOnAddress/WakeByAddressAll, _umtx_op 等内核 API 来实现。

在 C++20 之前没有直接的等价物,您必须直接使用条件变量或特定于平台的 API。