So, by now, we know how to create an application process with a few threads executing within it. We will repeat a code snippet from our very first demo program, ch14/pthreads1.c, as follows:
#include <pthread.h>
#define NTHREADS 3
[...]
int main(void)
{
[...]
for (i = 0; i < NTHREADS; i++) {
ret = pthread_create(&tid, NULL, worker, (void *)i);
if (ret)
FATAL("pthread_create() failed! [%d] ", ret);
}
[...]
Clearly, the process—well, we really mean the main thread of the process (or application)—goes in a loop, and each loop iteration creates a thread. So, when it's done, we will have three threads in addition to the main thread, which is a total of four threads, alive in the process.
This is obvious. The point here is this: creating threads is so much simpler than creating (child) processes with the fork(2); with fork, we had to carefully code it, getting the child to run its code while the parent continues with its code path (recall the switch-case construct; take another quick look at our ch10/fork4.c code example, if you wish to). With pthread_create(3), things have become easy for the application programmer – just call the API in a loop—and voila! You get as many threads as you like! In the preceding code snippet, imagine tweaking it, changing the value of NTHREADS from 3 to 300; and just like that, the process will produce 300 threads. What if we made NTHREADS 3,000? Or 30,000!?
Thinking about this brings up a couple of pertinent questions: one, how many threads can you actually create? And two, how many threads should you create? Please, read on.