Advertisement

pthread not giving back memory

Started by February 11, 2005 12:46 PM
4 comments, last by 255 19 years, 8 months ago
Hi everybody, I wrote the following test app to show my problem/question:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

pthread_t t;

void* function(void* p)
{
  printf("I am a Thread!\n");
  return 0;
}

int main()
{
  while(1)
    {
      pthread_create(&t,NULL,function,0);
      sleep(1);
    }
}
It starts a thread every second. The threads print something and exit. Now the problem: The more often a thread has been started, the more memory the application takes (I am watching with gnome-system-monitor). After ca. 30 threads it uses about 200MB of memory. It seems like the resources for the threads are not released when the threads finish. What is wrong, why is this happening? Any ideas? Thanks! PS: My gentoo-system uses NPTL
Yep, I see it too. Although it's all virtual, the memory is reserved but not used so it's not away from other processes. Weird though. Perhaps the memory get's freed but for some reason memory handler chooses to prolong the freeup..
Advertisement
EDIT: Never mind this post. return 0 implicitly calls pthread_exit()

Don't return from a thread. I don't know what behavior it will cause, but you should always end like:

void* my_thread(void* args) {...pthread_exit(NULL);}


Notice there's no return. Try that.
If I am intepretating the manpages correctly, it should not make a diffrence whether I call pthread_exit(0) or just do return 0;
I managed to stop the programm from consuming so much memory doing this:

...
int main()
{
while(1)
{
pthread_create(&t,NULL,function,0);
pthread_join(t,0);
sleep(1);
}
}
...

I do not unserstand ... but my programm works now.
Thanks for your help!!!
Nathan
Quote: Original post by LonelyStar
If I am intepretating the manpages correctly, it should not make a diffrence whether I call pthread_exit(0) or just do return 0;
I managed to stop the programm from consuming so much memory doing this:

...
int main()
{
while(1)
{
pthread_create(&t,NULL,function,0);
pthread_join(t,0);
sleep(1);
}
}
...

I do not unserstand ... but my programm works now.
Thanks for your help!!!
Nathan


pthread_join means wait for pthread_exit to be called. That way, you don't continually create hundreds/thousands of threads, you make them one at a time.

And note my comment about using pthread_exit over return; it functionally doesn't make a difference. pthread_exit is just the way I learned it.
man pthread_join says:
Quote:
When a joinable thread terminates, its memory resources (thread
descriptor and stack) are not deallocated until another thread performs
pthread_join on it. Therefore, pthread_join must be called once for
each joinable thread created to avoid memory leaks.

This topic is closed to new replies.

Advertisement