Port pthread_cond_broadcast to 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 中,这可以使用新的原子wait
和notify
操作来实现:
std::atomic<bool> MyVariableToBeSet;
bool SomeClass::waitMyVariableToBeSet() {
MyVariableToBeSet.wait(false);
}
void SomeClass::setMyVariable(bool newVal) {
MyVariableToBeSet = newVal;
MyVariableToBeSet.notify_all();
}
在内部,这些将使用队列的哈希映射或使用内核 API(如futex
、WaitOnAddress
/WakeByAddressAll
、_umtx_op
在可能的情况下实现。
在 C++20 之前没有直接等效项,您必须直接使用条件变量或特定于平台的 API。
> C++ 20 实现了解决方案
https://en.cppreference.com/w/cpp/atomic/atomic_flag
否则,我相信旋转锁将是随之而来的所有权衡的妥协。
相关文章:
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 在 lambda 表达式中使用 std::atomic
- C++std::atomic在程序员级别保证了什么
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- 在 C++20 之前和之后初始化 std::atomic
- std::atomic 和 std::mutex 的相对性能
- 简单使用 std::atomic 在两个线程之间共享数据
- Port pthread_cond_broadcast to std::atomic
- std::atomic中的任何内容都是免费等待的
- 为什么 std::atomic 构造函数在 C++14 和 C++17 中的行为不同
- std::atomic是如何实现的
- 使用 std::atomic 标志和 std::condition_variable 在工作线程上等待
- 为什么std::atomic的默认构造函数不默认初始化底层存储值
- 读取互斥对象范围之外的volatile变量,而不是std::atomic
- 为什么std::atomic中的所有成员函数都同时出现在有volatile和没有volatile的情况下
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 两个不同的进程,在同一地址上有 2 个 std::atomic 变量?
- 原子读取,然后使用 std::atomic 写入
- std::atomic::fetch_add是x86-64上的串行化操作
- 实际上,C++11 中 std::atomic 的内存占用量是多少?