c++简单多线程程序内存泄漏
C++ Simple multithreading program memory leak
我写了一个简单的代码,它应该创建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万个线程。生成线程并不便宜,而且您的平台不太可能同时运行多个线程。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏