c++ - pthread memory leak with stack variables -


i have noticed when call method using thread in form

////main code///// pthread_t thread; pthread_create(thread,function,data); //////////////////  void* function(void* data){      //work data on heap via vector on stack      std::vector<double> variable (100,1.2345);      //do contents of thread      pthread_exit(null); } 

despite having no calls new (except implicitly in vector variable) memory leak amount of memory usage going linearly number of times call function in way.

however if this

void* function(void* data){      {     std::vector<double> variable (100,1.2345);      //do contents of thread      }      pthread_exit(null); } 

the memory leak doesn't occur.

it seems pthread_exit(null)doesn't clear stack variables @ end of normal function return (i correct right?!) putting them within own scope ensures freed.

however, seems massive kludge. how ensure stack variables (and contents on heap in terms of containers) cleared when exiting pthread?

it seems pthread_exit(null) doesn't clear stack variables @ end of normal function return (i correct right?!)

that's calling exit(0) in non-threaded code, program exits right away , doesn't unwind stack. (since pthreads spec defined in terms of c, not c++, doesn't define happens c++ destructors, it's platform specific).

so putting them within own scope ensures freed.

because way vector's destructor runs before call pthread_exit().

how ensure stack variables (and contents on heap in terms of containers) cleared when exiting pthread?

just return thread function, don't need use pthread_exit exit thread start function (the 1 passed pthread_create). posix says:

an implicit call pthread_exit() made when thread other thread in main() first invoked returns start routine used create it.

and gnu/linux man page says same thing differently:

performing return start function of thread other main thread results in implicit call pthread_exit(), using function's return value thread's exit status.

you can use pthread_exit exit thread other functions further down stack, can use exit() quit program instead of returning main(), @ outermost function return null; (or whatever return value want).

the time using pthread_exit(x) makes difference return x; in main cause program wait until other threads finish.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -