【发布时间】:2015-08-14 23:56:32
【问题描述】:
我编写了一个简单的代码,它应该创建 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 main\n";
return 0;
}
【问题讨论】:
-
你没有显示任何内存分配的代码,那怎么可能有内存泄漏呢?
-
如何测量泄漏?
-
@Frophemida 如果内存消耗稳定,那么这不是内存泄漏。运行时库通常会保留已释放的内存,以防您稍后重新分配一些内存。这段代码 sn-p 中没有手动分配,所以很可能是发生了什么。
-
@Frophemida 我建议通过运行时分析器运行您的程序,它将报告任何未释放的内存。 Linux 有 Valgrind,here 是 Windows 的替代品列表。
-
好吧,你不应该产生 100 万个线程。
标签: c++ multithreading memory-leaks