以下代码在运行带有启用互斥保护的开关标志时会爆炸。即以./code.out 1运行
现在,核心转储的堆栈跟踪指向内存分配问题可能是因为线程中的每个插入都会导致整个向量的重新分配,因为大小最初超出了保留的内存。
跟踪是:
\#0 0x00007f1582ce6765 in raise () from /lib64/libc.so.6
\#1 0x00007f1582ce836a in abort () from /lib64/libc.so.6
\#2 0x00007f1582d27710 in __libc_message () from /lib64/libc.so.6
\#3 0x00007f1582d2feaa in _int_free () from /lib64/libc.so.6
\#4 0x00007f1582d3340c in free () from /lib64/libc.so.6
\#5 0x0000000000403348 in __gnu_cxx::new_allocator<int>::deallocate(int*, unsigned long) ()
\#6 0x00000000004029b2 in std::allocator_traits<std::allocator<int> >::deallocate(std::allocator<int>&, int*, unsigned long) ()
\#7 0x00000000004020ae in std::_Vector_base<int, std::allocator<int> >::_M_deallocate(int*, unsigned long) ()
\#8 0x0000000000401e4e in void std::vector<int, std::allocator<int> >::_M_emplace_back_aux<int const&>(int const&) ()
\#9 0x0000000000401707 in std::vector<int, std::allocator<int> >::push_back(int const&) ()
\#10 0x0000000000401212 in pushItem(int const&) ()
\#11 0x0000000000403d88 in void std::_Bind_simple<void (*(unsigned int))(int const&)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) ()
\#12 0x0000000000403cd3 in std::_Bind_simple<void (*(unsigned int))(int const&)>::operator()() ()
\#13 0x0000000000403c6e in std::thread::_State_impl<std::_Bind_simple<void (*(unsigned int))(int const&)> >::_M_run() ()
\#14 0x00007f158364f5cf in ?? () from /lib64/libstdc++.so.6
\#15 0x00007f15839235ca in start_thread () from /lib64/libpthread.so.0
\#16 0x00007f1582db50ed in clone () from /lib64/libc.so.6
当我运行与reserve(20)相同的程序时,它工作正常。问题是这里发生了什么。如果发生这种情况,我还假设有互斥保护,那么我缺少一些内在存在缺陷的东西 与矢量界面本身。请指导!!
#include<iostream>
#include<vector>
#include<mutex>
#include<thread>
#include<algorithm>
using namespace std;
std::vector<int> g_vector;
std::mutex g_mutex;
bool demoFlag = false;
void pushItem(const int& ref)
{
if(demoFlag)
{
cout << "Locking is enabled. so i am locking" << endl;
std::lock_guard<std::mutex> lock(g_mutex);
}
g_vector.push_back(ref);
}
int main(int argc, char* argv[])
{
if(argc == 2)
demoFlag = atoi(argv[1]);
g_vector.reserve(10);
for(unsigned int i=0; i<10; ++i)
g_vector.push_back(i);
std::vector<std::thread> threads;
for(unsigned int i=0; i<10; ++i)
threads.push_back(std::thread(pushItem,i));
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
for(const auto& ref : g_vector)
cout << "Item is = " << ref << " , ";
cout << endl;
}
答案 0 :(得分:1)
您的锁不会被使用。一些代码应该是这样的:
build/reports/tests/testReleaseUnitTest