????5.2 ???????
????????????????????????????????????????????????????????????????????????????????????????????pthread_detach??????????????????????ù????????????
????#include <pthread.h>
????int pthread_detach(pthread_t thread);
???????????£???????????????????????????????????????е?????????????????pthread_detach???????????????????????????????????????????????
/*
* ??????? thread_sample1.c
* ???????????????????
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
/*?????1??????*/
void *thread_routine1(void *arg)
{
fprintf(stdout?? "thread1: hello world! ");
sleep(1);
/*?????1??????*/
return NULL;
}
/*?????2??????*/
void *thread_routine2(void *arg)
{
fprintf(stdout?? "thread2: I'm running... ");
pthread_t main_thread = (pthread_t)arg;
/*????????????????????*/
pthread_detach(pthread_self());
/*?ж??????ID???????2ID??????*/
if (!pthread_equal(main_thread?? pthread_self())) {
fprintf(stdout?? "thread2: main thread id is not equal thread2 ");
}
/*???????????*/
pthread_join(main_thread?? NULL);
fprintf(stdout?? "thread2: main thread exit! ");
fprintf(stdout?? "thread2: exit! ");
fprintf(stdout?? "thread2: process exit! ");
/*?????2???????????????*/
pthread_exit(NULL);
}
int main(int argc?? char *argv[])
{
/*?????????1*/
pthread_t t1;
if (pthread_create(&t1?? NULL?? thread_routine1?? NULL)!=0) {
fprintf(stderr?? "create thread fail. ");
exit(-1);
}
/*????????1???*/
pthread_join(t1?? NULL);
fprintf(stdout?? "main thread: thread1 terminated! ");
/*?????????2???????????ID??????????2*/
pthread_t t2;
if (pthread_create(&t2?? NULL?? thread_routine2?? (void *)pthread_self())!=0) {
fprintf(stderr?? "create thread fail. ");
exit(-1);
}
fprintf(stdout?? "main thread: sleeping... ");
sleep(3);
/*????????pthread_exit????????????????????*/
fprintf(stdout?? "main thread: exit! ");
pthread_exit(NULL);
fprintf(stdout?? "main thread: never reach here! ");
return 0;
}
?????????н?????£?
thread1: hello world!
main thread: thread1 terminated!
main thread: sleeping...
thread2: I'm running...
thread2: main thread id is not equal thread2
main thread: exit!
thread2: main thread exit!
thread2: exit!
thread2: process exit!