I’m trying to create vtkPolyData from implicit functions.
But this code makes memory leak if I use std::thread.
Does anyone know the workarounds?
I’m using Linux debian11 and vtk 9.0.1 on x86_64 PC.
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h> // for getpid()
#include <vtkContourFilter.h>
#include <vtkSmartPointer.h>
#include <vtkSampleFunction.h>
#include <vtkSphere.h>
#include <vtkPolyData.h>
long getProcessMemKB()
{
static const long sz = getpagesize(); // bytes per a page
std::string statmPath = "/proc/" + std::to_string(getpid()) + "/statm";
std::ifstream ifs(statmPath.c_str());
if(ifs.fail()) {
return -1;
} else {
std::string buff;
ifs >> buff; // virtual memory (pages)
ifs >> buff; // physical memory (pages)
return static_cast<long>(std::stol(buff)*sz/1024);
}
}
std::pair<int, vtkSmartPointer<vtkPolyData>> create(int count)
{
auto sphereSource = vtkSmartPointer<vtkSphere>::New();
sphereSource->SetRadius(5.0);
auto sample = vtkSmartPointer<vtkSampleFunction>::New();
sample->SetImplicitFunction(sphereSource);
sample->SetModelBounds(-10, 10, -10, 10, -10, 10);
sample->SetSampleDimensions(100, 100, 100);
sample->Update();
auto surface = vtkSmartPointer<vtkContourFilter>::New();
surface->SetInputConnection(sample->GetOutputPort());
surface->Update();
auto polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->DeepCopy(surface->GetOutput());
return std::make_pair(count, polyData);
}
int main()
{
int count = 0;
while(true) {
std::pair<int, vtkSmartPointer<vtkPolyData>> retval;
// Memory leak occurs.
std::thread t([&](){retval = create(++count);});
t.join();
// If executing in main thread, it's OK.
// retval = create(++count);
std::cout << "count = " << retval.first << ", Memory(MB) = " << getProcessMemKB()/1000 << std::endl;
// doing something below in the actual code.
}
return 0;
}
In any setting (VTK_SMP_IMPLEMENTION_TYPE = OpenMP, sequential, TBB, or stdthread), the error message Class "vtkObjectFactoryCollection" has 1 instance still around. , which indicates a memory leak, will appear.
“VTK_SMP_IMPLEMENTION_TYPE = sequential” can not perfectly prevent memory leaks, but it can reduce the amount of leakage.