cancel
Showing results for 
Search instead for 
Did you mean: 

pthread_detach question

 
Highlighted
Occasional Contributor

pthread_detach question

Say I have a thread "tid" and I call pthread_detach(tid). Then in the thread itself I call pthread_exit. If I watch the process in glance and top, when the thread exits, since it's detached, shouldn't the memory (RSS/VSS in glance and SIZE and RES in top) go DOWN? I keep watching it and the memory usage doesn't go down and when I start another thread, the memory usage increases. This is 11.11 by the way.

This is my test program:

#define _MULTI_THREADED
#include
#include
#include

void *threadfunc(void *threadid)
{
void *status;

printf("In thread\n");
sleep(10);
printf("Exit thread\n");
pthread_exit(&status);
}

main()
{
pthread_t thread;
int rc, i;

printf("Start main()\n");

for (i = 0; i < 2; i++) {
rc = pthread_create(&thread, NULL, threadfunc, NULL);
printf("pthread_create returned %d\n", rc);
rc = pthread_detach(thread);
printf("pthread_detach returned %d\n", rc);
sleep(30);
}

printf("exit program\n");
exit(0);
}
4 REPLIES 4
Highlighted
Honored Contributor

Re: pthread_detach question

Hi Blanche,

It is printf() per thread buffer
Highlighted
Occasional Contributor

Re: pthread_detach question

I'm sorry?? I don't understand. I do know that if I take the above code and compile and run on a freeBSD system that the memory never budges. It doesn't go down when the thread exist but it also does not go up when a new thread is created.
Highlighted
Honored Contributor

Re: pthread_detach question

It seems that the reuse of a thread stack is one pthread_create behind the pthread_exit. I modified the test to print the address of the stack and to run a couple of parallel threads.
Each of the allocated stack address ranges was eventually reused. The stack of the most recently exited thread was not reused in the subsequent call to pthread_create.
Highlighted
Occasional Contributor

Re: pthread_detach question

Hmm... OK. So if I increase "i" to some big number and just let it run, after a while, my memory numbers should stablize since the memory for the old threads are being re-used right?