简体   繁体   English

C ++程序潜在的内存泄漏

[英]c++ program potential memory leak

I call the following void function() function every 40ms and I found that the memory consumption increase steadily. 我每40毫秒调用一次以下void function()函数,发现内存消耗稳步增加。 The consumption is not obvious at first but after days, the consumption is huge. 起初消耗不明显,但几天后,消耗巨大。 Can anyone help to explain what is wrong with this code. 任何人都可以帮助解释此代码有什么问题。 Is it a thread problem or std::move problem that caused the memory leak. 是导致内存泄漏的线程问题还是std::move问题。

void do_task(const std::vector<int>& tmp)
{
    // do some work here
}

void function()
{
    std::vector<std::thread> task;
    std::vector<int> tmp1, tmp2;

    GetTempValue(tmp1);
    GetTempValue(tmp2);

    task.push_back(std::thread(do_task, std::move(tmp1)));
    task.push_back(std::thread(do_task, std::move(tmp2)));

    tmp1.clear();
    tmp2.clear();

    UpdateTempValue(tmp1);
    UpdateTempValue(tmp2);

    task.push_back(std::thread(do_task, std::move(tmp1)));
    task.push_back(std::thread(do_task, std::move(tmp2)));

    tmp1.clear();
    tmp2.clear();

    for(int i=0; i<task.size(); i++)
    {
        task[i].join();
    }
}

Passing a reference to a thread is a big no-no. 将引用传递给线程是一个很大的禁忌。 Or at least a bug waiting to happen... 或至少有一个错误等待发生...

You should try redefining do task to accept a std::vector by value. 您应该尝试重新定义do任务以按值接受std :: vector。 Isn't that what you were trying to do anyway by calling std::move to pass them to the threads? 那不是通过调用std :: move将它们传递给线程来尝试做的事情吗?

Change the definition of do_task to: 将do_task的定义更改为:

void do_task(std::vector<int> tmp);

I've made some quick calculations. 我做了一些快速的计算。 If the threads started by function() leak, by starting 4 threads every 40ms, you should have a leak rate of over 1.4MB/hour. 如果由function()启动的线程泄漏,则每40ms启动4个线程,则泄漏率应超过1.4MB /小时。 If your leak is less than that, you should start looking elsewhere in your code. 如果泄漏小于此值,则应开始在代码中查找其他位置。

In any case, starting 100 threads per second is not really efficient. 无论如何,每秒启动100个线程并不是很有效。 A big chunk of your computing power is lost in creating threads. 创建线程会损失大量计算能力。 Have you considered other options? 您是否考虑过其他选择?

Having 4 threads running endless loops, and queuing the work to them will be way more efficient, less taxing on the OS, and less prone to leaks that you cannot control. 让4个线程运行无穷循环,并将工作排队,将更加高效,减少操作系统负担,并减少不易控制的泄漏。

I think openmp may be interresting. 我认为openmp可能很有趣。 OpenMP is an API for developing parallel applications. OpenMP是用于开发并行应用程序的API。

https://en.m.wikipedia.org/wiki/OpenMP https://en.m.wikipedia.org/wiki/OpenMP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM