xml*_*lmx 3 c++ multithreading mutex atomic c++11
我有一个int32_t初始值 42。现在我希望它可以被多个线程原子访问。
#include <atomic>
using namespace std;
int32_t* pn{};
int main()
{
pn = getPtrFromMmap();
assert(42 == *pn); // note that *pn is mapped to a disk file
// How to make the following two threads access *pn atomically?
std::thread{[&]{ (*pn)++; }}.detach();
std::thread{[&]{ (*pn)++; }}.detach();
}
Run Code Online (Sandbox Code Playgroud)
编写一个正确的原子操作类并不是一件小事。所以,我试图用它std::atomic来实现我的目标,但失败了。
std::atomic在这种情况下有没有办法重用?
不。
std::atomic大致认为
template <typename T>
class atomic {
T value;
public:
// a bunch of member functions
};
Run Code Online (Sandbox Code Playgroud)
即 astd::atomic<int32_t> 包含一个int32_t。
你需要的是一个
template <typename T>
class atomic_ref {
T & ref;
public:
// a bunch of member functions
};
Run Code Online (Sandbox Code Playgroud)
这种类型不是 的成员std::。
在 C++17std::atomic<std::reference_wrapper<T>>中保证是有效的,但在这里没有帮助。对所指对象的操作不是原子的。
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |