std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1()
{
std::shared_ptr<int>l_s1 = g_s; // read g_s
}
void f2()
{
std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
std::thread th(f1);
th.detach();
g_s = l_s2; // write g_s
}
关于上面的代码,我知道不同的线程读取和写入相同的内容shared_ptr
导致竞争条件。但怎么样weak_ptr
?下面的代码中是否存在竞争条件? (我的平台是Microsoft VS2013。)
std::weak_ptr<int> g_w;
void f3()
{
std::shared_ptr<int>l_s3 = g_w.lock(); //2. here will read g_w
if (l_s3)
{
;/.....
}
}
void f4()
{
std::shared_ptr<int> p_s = std::make_shared<int>(1);
g_w = p_s;
std::thread th(f3);
th.detach();
// 1. p_s destory will motify g_w (write g_w)
}
我知道我迟到了,但是在搜索“weak_ptr thread”时会出现这种情况,而凯西的答案并不是全部事实。Both shared_ptr
and weak_ptr
可以从线程中使用而无需进一步同步。
For shared_ptr
,有很多文档(例如cppreference.com http://en.cppreference.com/w/cpp/memory/shared_ptr or on 堆栈溢出 https://stackoverflow.com/questions/9127816)。您可以安全地访问shared_ptr
是从不同线程指向同一个对象。你只是不能从两个线程敲击同一个指针。换句话说:
// Using p and p_copy from two threads is fine.
// Using p from two threads or p and p_ref from two threads is illegal.
std::shared_ptr<A> p = std::make_shared<A>();
std::shared_ptr<A> &p_ref = p;
std::shared_ptr<A> p_copy = p;
要解决代码中的该问题,请传递g_s
作为参数(按值)* 到f1()
.
对于弱指针,安全保证隐藏在文档中弱指针::锁 http://en.cppreference.com/w/cpp/memory/weak_ptr/lock:
有效回报expired() ? shared_ptr<T>() : shared_ptr<T>(*this)
,原子执行。
您可以使用weak_ptr::lock()
得到一个shared_ptr
来自其他线程,无需进一步同步。这也得到了证实here http://www.boost.org/doc/libs/1_58_0/libs/smart_ptr/weak_ptr.htm对于升压和在这个答案 https://stackoverflow.com/a/2160422/25097作者:克里斯·杰斯特·杨。
再次强调,你必须确保不要修改相同的内容weak_ptr
从一个线程访问它,同时从另一个线程访问它,所以通过g_w
into f3()
也按价值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)