【发布时间】:2013-11-16 20:06:09
【问题描述】:
在线程 1(转述代码)中:
std::vector<std::shared_ptr<Object>> list;
// Initialization
list.reserve(prop_count);
for (size_t i = 0; i < count; ++i)
{
list.push_back(std::shared_ptr<Object>());
}
// Looped code
for (auto iter = indexes.begin(); iter != indexes.end(); ++iter)
{
uint32_t i = *iter;
std::shared_ptr<Object> item = make_object(table->data[i]); // returns a shared_ptr of Object
list[i].swap(item);
}
在线程 2 中(转述代码):
for(auto iter = list.begin(); iter != list.end(); ++iter)
{
shared_ptr<Property> o(*iter);
if(o)
{
// some work with casting it
// dynamic_pointer_cast
}
} // <--- crashes here (after o is out of scope)
这里是调用栈:
0x006ea218 C/C++
std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)1>::_M_release(this = 0x505240) C/C++
std::__shared_count<(__gnu_cxx::_Lock_policy)1>::~__shared_count(this = 0xb637dc94) C/C++
std::__shared_ptr<Property, (__gnu_cxx::_Lock_policy)1>::~__shared_ptr(this = 0xb637dc90) C/C++
std::shared_ptr<Property>::~shared_ptr(this = 0xb637dc90) C/C++
startSending() C/C++
libpthread.so.0!start_thread() C/C++
libc.so.6 + 0xb52b8 C/C++
查看shared_ptr_base.h,这里好像崩溃了:
if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, -1) == 1)
{
_GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count);
_M_dispose(); // <--- HERE
我不确定如何解决这个问题。任何帮助表示赞赏。谢谢!
【问题讨论】:
-
一个线程修改列表,而一个线程在没有任何互斥锁的情况下读取它。为什么你认为它应该有效?
-
它似乎并没有一直崩溃。有时它不会崩溃很长时间。其他时候它会崩溃。似乎完全是随机的。但是两个线程都在不断地访问列表。
-
欢迎来到线程的乐趣。我建议你查一下
std::mutex。
标签: c++ multithreading thread-safety shared-ptr