Port pthread_cond_broadcast to std::atomic

Port pthread_cond_broadcast to std::atomic

本文关键字:std atomic to broadcast pthread cond Port      更新时间:2023-10-16

试图理解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 中,这可以使用新的原子waitnotify操作来实现:

std::atomic<bool> MyVariableToBeSet;
bool SomeClass::waitMyVariableToBeSet() {
MyVariableToBeSet.wait(false);
}
void SomeClass::setMyVariable(bool newVal) {
MyVariableToBeSet = newVal;
MyVariableToBeSet.notify_all();
}

在内部,这些将使用队列的哈希映射或使用内核 API(如futexWaitOnAddress/WakeByAddressAll_umtx_op在可能的情况下实现。

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

> C++ 20 实现了解决方案

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

否则,我相信旋转锁将是随之而来的所有权衡的妥协。