title: pthread_attr_setstacksize and pthread_exit
body: <p>I have a question about C concurrency programming in Embedded System with about 64Mb Ram.
  Especially, I want to reduce the default memory used by a Thread, so I have defined:</p>
  
  <pre><code>pthread_attr_t attr_test;
  size_t stacksize = 0x186A0; // 100Kbyte
  pthread_attr_init(&amp;attr_test);
  pthread_attr_setdetachstate(&amp;attr_test, PTHREAD_CREATE_DETACHED);    
  pthread_attr_setstacksize(&amp;attr_test, stacksize);
  </code></pre>
  
  <p>So, When the Thread starts, it uses only 100Kbyte of virtual Memory.
  BUT when the Thread ends and calls pthread_exit, the virtual Memory used by the process, increases rapidly!....</p>
  
  <p>Why? What can I do?</p>
  
  <p>Thanks!</p>
  
  <p><strong>UPDATE</strong>:</p>
  
  <p><strong><em>Thread -></em></strong></p>
  
  <pre><code>void *thread_test(void *arg1) {
      int *param;
      param = (int*)arg1;
  
      printf("Thread %d start\n", *param);
      pthread_cond_wait(&amp;condition[*param], &amp;mutex[*param]);
      printf("Thread %d stop\n",*param);
      pthread_exit(0);
  }
  </code></pre>
  
  <p><strong><em>Main -></em></strong></p>
  
  <pre><code>int main(void) {
      pthread_t IDthread[MAX_THREADS];
      int param[MAX_THREADS];
      int pointer;
      int i, keyb;
      void *stkaddr;
      size_t stacksize;
  
      puts("!!! THREAD TEST !!!");
      printf("Process ID %d\n\n", getpid());
  
      for(i=0; i&lt;MAX_THREADS; i++)
      {
          pthread_cond_init(&amp;condition[i], NULL);
          pthread_mutex_init(&amp;mutex[i], NULL);
          IDthread[i] = 0;
          param[i] = i;
  
      }
  
      stacksize = 0x186A0; // 100Kbyte
  
      pthread_attr_init(&amp;attr_test);
  
      pthread_attr_setdetachstate(&amp;attr_test, PTHREAD_CREATE_DETACHED);
      /* setting the size of the stack also */
      pthread_attr_setstacksize(&amp;attr_test, stacksize);
  
      pointer = 0;
  
  
      do {
          keyb = getchar();
          if (keyb == '1')
          {
              if (pointer &lt; MAX_THREADS)
              {
                  pthread_create(&amp;IDthread[pointer], &amp;attr_test, thread_test, &amp;param[pointer]);
                  sleep(1);
                  pointer++;
              }
              else
                  puts("MAX Threads Number");
          }
  
          if (keyb == '2')
          {
              if (pointer != 0)
              {
                  pointer--;
                  pthread_cond_signal(&amp;condition[pointer]);
                  sleep(1);
              }
              else
                  puts("0 Thread is running");
          }
  
      } while (keyb != '0');
      printf("FINE\n");
      return EXIT_SUCCESS;
  
  }
  </code></pre>