//beginging linux programming ch12
[root@localhost ch12]# cat thread5.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int thread_finished = 0;
int res;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr);
if (res != 0) {
perror("Attribute creation failed");
exit(EXIT_FAILURE);
}
res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
if (res != 0) {
perror("Setting detached attribute failed");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread,NULL, thread_function, (void *)message);
//&thread_attr
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
(void)pthread_attr_destroy(&thread_attr);
res = pthread_join(a_thread, &thread_result);
printf("Other thread finished, bye!\n");
// pthread_exit(NULL);
exit(0);
}
void *thread_function(void *arg) {
printf("thread_function is running. Argument was %s\n", (char *)arg);
sleep(1);
printf("Second thread setting finished flag, and exiting now\n");
thread_finished = 1;
pthread_exit(NULL);
}
[root@localhost ch12]# make
cc -D_REENTRANT -lpthread thread5.c -o thread5
[root@localhost ch12]# ./thread5
thread_function is running. Argument was Hello World
Second thread setting finished flag, and exiting now
Other thread finished, bye!
[root@localhost ch12]#
modify line31 shown below res = pthread_create(&a_thread,&thread_attr, thread_function, (void *)message);
then[root@localhost ch12]# ./thread5
Other thread finished, bye!
[root@localhost ch12]#
可见用NULL创建的子线程,主线程可用pthread_join使自己等待子线程结束(主线程阻塞在pthread_join的位置)
而用DETACH创建的子线程,主线程用pthread_join也不会使自己阻塞,而是一直执行