views:

54

answers:

2

Hi,

I am using C language and Linux as my programming platform.

In my user-space application. I used pthread to create a thread.

int main()
{
   pthread_t thread1, thread2;
   pthread_create( &thread1, NULL, fthread1, NULL );
   pthread_create( &thread2, NULL, fthread2, NULL );

   return 0;
}

void *fthread1( void *ptr )
{
   /* do something here */
   pthread_exit( NULL );
}

void *fthread2( void *ptr )
{
   /* do something here */  
   pthread_exit( NULL );
}

My problem is when I loop pthread_create to create again the two thread, my application memory usage is getting bigger.

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
}

I determine the memory usaage using Linux ps command-line tool in VSZ column.

It seems I missed some part using pthreads API. How can I make my app don't use too much memory.

+5  A: 

You are potentially creating threads when the thread is still running/hasn't started. This is undefined behavior. (Read: very bad)

If you modify your program to do:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1, NULL);
   pthread_join(&thread2, NULL);
}

you will wait for the thread to complete before starting a new thread.

Note that each thread has its own call stack and control structures, and will consume memory. It is best to limit the number of threads in an application, and to not create and destroy threads in a rapid fashion.

Yann Ramin
@theatrus: both our inventions jump and meet in one! (cf. The Taming of the Shrew).
Tim Schaeffer
+4  A: 

Before looping around to create new threads, make sure the present ones have finished:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1);
   pthread_join(&thread2);
}

You are creating threads faster than the processor can clean them up.

Tim Schaeffer