c++简单多线程程序内存泄漏

C++ Simple multithreading program memory leak

本文关键字:内存 泄漏 程序 多线程 简单 c++      更新时间:2023-10-16

我写了一个简单的代码,它应该创建1000个线程,做一些工作,连接它们,并重播1000次。

我有一个内存泄漏与这段代码,我不明白为什么。我一直在到处寻找解决办法,但就是找不到。
#include <iostream>
#include <thread>
#include <string>
#include <windows.h>

#define NUM_THREADS 1000
std::thread t[NUM_THREADS];
using namespace std;

//This function will be called from a threads
void checkString(string str)
{
    //some stuff to do
}
void START_THREADS(string text)
 {
    //Launch a group of threads
    for (int i = 0; i < NUM_THREADS; i++)
    {
        t[i] = std::thread(checkString, text);
    }

    //Join the threads with the main thread
    for (int i = 0; i < NUM_THREADS; i++) {
        if (t[i].joinable())
        {
            t[i].join();
        }
    }
    system("cls");
 }

int main() 
{
    for(int i = 0; i < 1000; i++)
    {
        system("cls");
        cout << i << "/1000" << endl;
        START_THREADS("anything");
    }

    cout << "Launched from the mainn";
    return 0;
}

我不确定内存泄漏,但您肯定有内存错误。你不应该这样做:

delete &t[i];

t[i]没有被分配给new,也不可能是delete d.您可以安全地删除这一行。

至于内存消耗,您需要问自己是否真的需要生成100万个线程。生成线程并不便宜,而且您的平台不太可能同时运行多个线程。