on threads under linux

Other questions that come up about threads

How many threads can I run? This depends on a number of things

  • The ulimit of the user. Set the number of threads with ulimit -u (or somewhere like /etc/security/limits.conf).

  • The default stack size. By default, the stack size of a new thread is quite large, in the region of megabytes. It's not going to take you long to run out of memory for new stacks. Luckily, pthread_attr_setstacksize() allows you use smaller stacks.

  • The kernel. The kernel won't allow you to fill up your entire memory with thread descriptors. See kernel/fork.c:fork_init()

    /*
      * The default maximum number of threads is set to a safe
      * value: the thread structures can take up at most half
      * of memory.
      */
      max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
    

    I belive this works out to around 4000 threads on a 256Mb x86 machine; YMMV of course.

What does ps show me? By default, ps should only show you the parent thread. Try with -m for the child threads.