一个线程或者是可汇合的(joinable,缺省值),或者是脱离的(detached)。当一个可汇合的线程终止时,它的线程ID和退出状态将留到另一个线程对它调用pthread_join。脱离线程却象守护进程:当它们终止的时,所有相关资源都被释放,我们不能等待它们终止。如果一个线程需要知道另一个线程什么时候终止,那就最好好吃第二个线程的可汇合状态。
创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源(类似于wait,waitpid)
但是调用pthread_join(pthread_id)后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此,比如在Web服务器中当主线程为每个新来的链接创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码
pthread_detach(pthread_self())
或者父线程调用
pthread_detach(thread_id)(非阻塞,可立即返回)
这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。
join
- join是三种同步线程的方式之一。另外两种分别是互斥锁(mutex)和条件变量(condition variable)。
- 调用pthread_join()将阻塞自己,一直到要等待加入的线程运行结束。
- 可以用pthread_join()获取线程的返回值。
- 一个线程对应一个pthread_join()调用,对同一个线程进行多次pthread_join()调用是逻辑错误。
join or detach
- 线程分两种:一种可以join,另一种不可以。该属性在创建线程的时候指定。
- joinable线程可在创建后,用pthread_detach()显式地分离。但分离后不可以再合并。该操作不可逆。
- 为了确保移植性,在创建线程时,最好显式指定其join或detach属性。似乎不是所有POSIX实现都是用joinable作默认。
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM_THREADS 4
- void *BusyWork(void *t)
- {
- double result=0.0;
- long tid = (long)t;
- printf("Thread %ld starting...\n",tid);
- for (int i=0; i<1000000; i++)
- {
- result = result + sin(i) * tan(i);
- }
- printf("Thread %ld done. Result = %e\n",tid, result);
- pthread_exit((void*) t);
- }
- int main (int argc, char *argv[])
- {
- pthread_t thread[NUM_THREADS];
- pthread_attr_t attr;
- // 1/4: init
- pthread_attr_init(&attr);
- // 2/4: explicitly specify as joinable or detached
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
- int rc;
- long t;
- for(t=0; t<NUM_THREADS; t++)
- {
- printf("Main: creating thread %ld\n", t);
- // 3/4: use thread attribute
- rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
- if (rc) {
- printf("ERROR; return code from pthread_create() is %d\n", rc);
- exit(-1);
- }
- }
- // 4/4: release thread attribute
- pthread_attr_destroy(&attr);
- void *status;
- for(t=0; t<NUM_THREADS; t++)
- {
- rc = pthread_join(thread[t], &status);
- if (rc) {
- printf("ERROR; return code from pthread_join() is %d\n", rc);
- exit(-1);
- }
- printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
- }
- printf("Main: program completed. Exiting.\n");
- return 0;
- }
总结:
pthread_join()会挂起父线程,直至子线程完成才可以执行后面的代码,此外,一个PTHREAD_CREATE_JOINABLE状态的子线程不会自动释放该线程的内存资源,包括线程描述符和其使用的栈;而主线程调用pthread_detach()时,无需等待子线程的完成,它可以立即执行后面的代码,当然,也有可能主线程执行完之后销毁进程,导致子线程未能执行,此外,一个PTHREAD_CREATE_DETACH状态的子线程拥有自我回收内存资源的功能