In the initial thread, the thread "start function" (main) is called from outside your program; for example, many UNIX systems link your program with a file called crt0.o, which initializes the process and then calls your main. This is a minor implementation distinction, but it is important to remember because there are a few ways in which the initial thread is different. For one thing, main is called with different arguments than a thread start function: the program's argument array (argc and argv) instead of a single void* argument. For another thing, when a thread start function returns, the thread terminates but other threads continue to run. When the function main returns in the initial thread, the process will be terminated immediately. If you want to terminate the initial thread while allowing other threads in the process to continue running, call pthread_exit instead of returning from main.
Another important difference to remember is that on most systems, the initial thread runs on the default process stack, which can grow to a substantial size. "Thread" stacks may be much more limited on some implementations, and the program will fail with a segmentation fault or bus error if a thread overflows its stack.
2.2.3 Running and blocking
Like us, threads usually can't stay awake their entire life. Most threads occasionally go to sleep. A thread can go to sleep because it needs a resource that is not available (it becomes "blocked") or because the system reassigned the processor on which it was running (it is "preempted"). A thread spends most of its active life in three states:
A thread becomes
When a thread is unblocked after a wait for some event, it is made
2.2.4 Termination
A thread usually terminates by returning from its start function (the one you pass to the pthread_create
function). The thread shown in lifecycle.c terminates by returning the value NULL, for example. Threads that call pthread_exit
or that are canceled using pthread_cancel
also terminate after calling each cleanup handler that the thread registered by calling pthread_cleanup_push
and that hasn't yet been removed by calling pthread_cleanup_pop. Cleanup handlers are discussed in Section 5.3.3.
Threads may have private "thread-specific data" values (thread-specific data is discussed in Section 5.4). If the thread has any non-NULL thread-specific data values, the associated destructor functions for those keys (if any) are called.