I have problem with memory management with std::string.
I have application - multithread server with detached threads (i done need to join them, they will do the job and exit) and i found that after a while memory usage comes quite high. I've started to experiment where is the problem and i've created test program which demonstrating the problem
#include <iostream>
#include <string>
#include <pthread.h>
pthread_t thread[100];
using namespace std;
class tst {
public:
tst() {
//cout << "~ Create" << endl;
}
~tst() {
//cout << "~ Delete" << endl;
}
void calc() {
string TTT;
for (int ii=0; ii<100000; ii++) {
TTT+="abcdenbsdmnbfsmdnfbmsndbfmsndb ";
}
}
};
void *testThread (void *arg) {
int cnt=*(int *) arg;
cout << cnt << " ";
tst *TEST=new tst;
TEST->calc();
delete TEST;
pthread_exit((void *)0);
}
int main (int argc, char * const argv[]) {
cout << "---------------------------------------------------" << endl;
sleep(5);
for (int oo=0; oo<100; oo++) {
pthread_create(&thread[oo], NULL, testThread, &oo);
pthread_detach(thread[oo]);
}
cout << endl;
cout << "---------------------------------------------------" << endl;
sleep(5);
for (int oo=0; oo<100; oo++) {
pthread_create(&thread[oo], NULL, testThread, &oo);
pthread_detach(thread[oo]);
}
cout << endl;
cout << "---------------------------------------------------" << endl;
sleep(5);
exit(0);
}
after first "---" the memory usage is 364KB, after second its 19MB, after third is 33.5MB. there is 1 strange thing as well - each run showing different memory usage but mostly the last memory usage is about 50% more then after the second "---".
i've expected that if the class TEST (tst) is deleted then the string will release its memory as well - i found that threads will not do that - that's why i'm creating new tst, running it and then delete.
in my program this causing a big problem because i'm using there few strings in each thread and after a while the memory usage is over gig ;-(
is there any option how to 'empty' the memory after string?
i've tried TTT="" or TTT.clear() without any change.
...i need to use threads - it will be running on multicpu machine where threads is the only option to use it's 'full power' (as i know)