Yoc*_*mer 18 c++ multithreading
假设我有一个指向整数的指针.
volatile int* commonPointer = new int();
Run Code Online (Sandbox Code Playgroud)
我有多个线程可以取消引用该指针.
int blah = *commonPointer;
Run Code Online (Sandbox Code Playgroud)
但是,一个线程需要更改指针的地址:
int* temp = new int();
int* old = commonPointer;
InterlockedExchange(&commonPointer,temp);
delete old;
Run Code Online (Sandbox Code Playgroud)
现在,让我们忽略一些线程可能正在读取"旧"值的事实,而有些线程可能正在读取"新"值,这在我的情况下不是问题.
是否存在一个线程开始取消引用指针的情况,就像删除地址一样,然后获得异常?
或者解除引用足够的原子以便不会发生?
sya*_*yam 22
在这种情况下,C++标准中没有任何内容可以保证原子性.
您必须使用互斥锁保护相关代码区域:即使std::atomic
还不够,因为它只提供对指针的原子访问,但不包括取消引用操作.
也许,C++11
atomic<shared_ptr<int> >
Run Code Online (Sandbox Code Playgroud)
满足您的需求。它可以防止旧值消失,直到至少一个对该值的引用有效。
atomic<shared_ptr<int> > commonPointer;
// producer:
{
shared_ptr<int> temp(new int);
shared_ptr<int> old= atomic_exchange(&commonPointer, temp);
//...
};// destructor of "old" decrements reference counter for the old value
// reader:
{
shared_ptr<int> current= atomic_load(&commonPointer);
// the referent pointed by current will not be deleted
// until current is alive (not destructed);
}
Run Code Online (Sandbox Code Playgroud)
但是,原子共享 ptr 的无锁实现足够复杂,因此可能会在库实现中使用锁或自旋锁(即使该实现在您的平台上可用)。