I'm struggling with a (strange?) behavior when resizing vectors in subthreads.
The virtual memory consumption increases a lot when vector<T>.reserve
is called in a subthread (or when a reallocation appends on adding elements) compared to the same code called in the main process.
I had a similar issue on vector.swap
that can be solved thanks to std::swap
.
In short, is there a way to safely resize a vector in a subthread, and what does cause such a behavior ?
I can put sample code if needed.
Thanks in advance ;)
EDIT
@david Haim : there is indeed a reference, and its extracted from a library with unitary tests and the original vector is modified as expected.
@user0042 : there is no synchronization but no concurrency either.
Here is a small code.
The memory monitoring comes from this post
#include <iostream>
#include <vector>
#include <thread>
typedef std::vector< int > VectInt_t;
void init(VectInt_t &vec_p)
{
vec_p.reserve(500);
}
void resize(VectInt_t &vec_p)
{
vec_p.resize(2000);
}
// ==========================================================================
int main(int argc, char ** argv)
{
int cas_l(0);
if(argc > 1)
{
cas_l = atol(argv[1]);
}
VectInt_t myVec_l;
init(myVec_l);
//std::cout << "After init : " << std::endl
//<< "\tVirtualMemoryUsedByCurrentProcess = " << getVirtualMemoryUsedByCurrentProcess() << std::endl
//<< "\tPhysicalMemoryUsedByCurrentProcess = " << getPhysicalMemoryUsedByCurrentProcess() << std::endl;
switch(cas_l)
{
case 0:
{
resize(myVec_l);
break;
}
case 1:
{
std::thread thread_l(resize, std::ref(myVec_l));
thread_l.join();
std::cout << "thread done" << std::endl;
break;
}
}
//std::cout << "After resize : " << std::endl
//<< "\tVirtualMemoryUsedByCurrentProcess = " << getVirtualMemoryUsedByCurrentProcess() << std::endl
//<< "\tPhysicalMemoryUsedByCurrentProcess = " << getPhysicalMemoryUsedByCurrentProcess() << std::endl;
return 0;
}
The result gives (on debian 9) :
$ ./minCase 0
After init :
VirtualMemoryUsedByCurrentProcess = 15252
PhysicalMemoryUsedByCurrentProcess = 1724
After resize :
VirtualMemoryUsedByCurrentProcess = 15252
PhysicalMemoryUsedByCurrentProcess = 1724
$ ./minCase 1
After init :
VirtualMemoryUsedByCurrentProcess = 15252
PhysicalMemoryUsedByCurrentProcess = 1688
thread done
After resize :
VirtualMemoryUsedByCurrentProcess = 88984
PhysicalMemoryUsedByCurrentProcess = 1700