简体   繁体   English

将 pthread_cond_broadcast 移植到 std::atomic

[英]Port pthread_cond_broadcast to std::atomic

Trying to understand all the in and out of std::atomic (lock-free operations in C++ 11).试图了解 std::atomic 的所有进出(C++ 11 中的无锁操作)。

I was wondering if an operation like this:我想知道是否有这样的操作:

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

AND

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

Could be replace like this with std::atomic:可以像这样用 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 implemented the solution C++ 20 实现解决方案

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

Otherwise, I believe a spinlock would be the compromise with all trade off that comes with it.否则,我相信自旋锁将是与随之而来的所有权衡的妥协。

With C++20 this can be implemented using new atomic wait and notify operations:在 C++20 中,这可以使用新的原子waitnotify操作来实现:

std::atomic<bool> MyVariableToBeSet;

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

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

Internally those will be implemented using a hash map of queues or using kernel APIs such as futex , WaitOnAddress / WakeByAddressAll , _umtx_op when possible.在内部,这些将使用队列的 hash map 或使用 kernel API(例如futexWaitOnAddress / WakeByAddressAll_umtx_op实现

Before C++20 there is no direct equivalent and you have to use condition variables or platform-specific APIs directly.在 C++20 之前,没有直接的等价物,您必须直接使用条件变量或特定于平台的 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM