std 线程向量的 valgrind 输出中仍然可到达的块

Ana*_*rni 2 c++ multithreading valgrind c++11

我有下面的代码,当在 valgrind 下运行时显示仍然说一些块是可访问的。尽管代码没有任何显式泄漏。为什么会发生这种情况。

请帮忙?

valgrind 跟踪是

==5059== 32 bytes in 1 blocks are still reachable in loss record 1 of 1
==5059==    at 0x4C2C20C: operator new(unsigned long) (vg_replace_malloc.c:334)
==5059==    by 0x402A67: __gnu_cxx::new_allocator<std::thread>::allocate(unsigned long, void const*) (new_allocator.h:104)
==5059==    by 0x402986: std::allocator_traits<std::allocator<std::thread> >::allocate(std::allocator<std::thread>&, unsigned long) (alloc_traits.h:416)
==5059==    by 0x40280F: std::_Vector_base<std::thread, std::allocator<std::thread> >::_M_allocate(unsigned long) (stl_vector.h:170)
==5059==    by 0x402493: void std::vector<std::thread, std::allocator<std::thread> >::_M_emplace_back_aux<std::thread>(std::thread&&) (vector.tcc:412)
==5059==    by 0x402008: void std::vector<std::thread, std::allocator<std::thread> >::emplace_back<std::thread>(std::thread&&) (vector.tcc:101)
==5059==    by 0x40188F: std::vector<std::thread, std::allocator<std::thread> >::push_back(std::thread&&) (stl_vector.h:933)
==5059==    by 0x4012D0: main (t3.cpp:25)

==5059== LEAK SUMMARY:
==5059==    definitely lost: 0 bytes in 0 blocks
==5059==    indirectly lost: 0 bytes in 0 blocks
==5059==      possibly lost: 0 bytes in 0 blocks
==5059==    still reachable: 32 bytes in 1 blocks
==5059==         suppressed: 0 bytes in 0 blocks
==5059== 
Run Code Online (Sandbox Code Playgroud)

代码如下。

#include<iostream>
#include<vector>
#include<string>
#include<mutex>
#include<thread>

using namespace std;

std::mutex g_mutex;

void dosomework(const int& id)
{
    std::lock_guard<std::mutex> lock(g_mutex);
    cout << "I am doing some work in thread id = " << id << endl;
}


int main(int argc, char* argv[])
{

    std::vector<std::thread> threads;
    threads.reserve(3);

    for(unsigned int i=0; i<3; ++i)
        threads.push_back(std::thread(dosomework,i));

    std::this_thread::sleep_for(std::chrono::seconds(10));

    for(auto& t : threads)
    {

        if(t.joinable())
        {
            cout << "joining the thread" << endl;
            t.join();
        }
        else
        {
            cout << "thread is not joinable" << endl;
        }
    }

    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

doq*_*tor 5

那是因为exit(0)被调用而不是return 0从你的main().

return被调用时main(),析构函数将被调用以获取局部范围的对象,而如果exit()被调用,则情况并非如此!

  • 是的,基础知识!!我错过了那个。使用 exit 是个坏主意,几乎应该总是避免它。 (2认同)