今天apue 的线程章节学习线程退出时,书上对 pthread_exit()和pthread_join 函数的说明不是很详细,看了一个例子还是不理解,说的太过官方
那么先介绍一下
pthread_join(pthread_join thread, void **rval_ptr)
thread = 线程ID , rval_ptr = pthread_exit()的参数,也就是说pthread_exit() 函数的参数是这个线程的返回值,当线程结束后join 函数可以获取他的返回值
pthread_exit(void *rval_ptr)
线程里边不能使用exit _exit _Exit 函数退出,这样会导致进程退出,所以一般使用pthread_exit 函数或者直接return的方式进行退出 那么这个函数的参数是干啥的
rval_ptr 就相当于返回值 join 可以接受到
使用例子书上都谈一下书上说的一个陷阱,需要注意的地方
#include "apue.h"
#include <pthread.h>
struct foo {
int a, b, c, d;
};
void printfoo(const char *s , const struct foo *fp){
printf("%s, ",s);
printf(" struct at 0x%lx\n", (unsigned long)fp);
printf(" foo.a = %d\n", fp->a);
printf(" foo.b = %d\n", fp->b);
printf(" foo.c = %d\n", fp->c);
printf(" foo.d = %d\n", fp->d);
}
void * thr_fn1(void *arg){
struct foo foo = {1,2,3,4};
printfoo("thread 1:\n", &foo);
pthread_exit((void *)&foo);
}
void * thr_fn2(void *arg){
printf("thread 2: ID is %lu \n", (unsigned long)pthread_self());
pthread_exit((void *)0);
}
int main(void){
int err;
pthread_t tid1, tid2;
struct foo *fp;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0){
err_exit(err, "can't crate thread 1");
}
err = pthread_join(tid1, (void *)&fp);
if (err != 0){
err_exit(err, "can't join with thread 1");
}
sleep(1);
printf("parent starting second thread \n");
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0){
err_exit(err, "can't crate thread 2");
}
sleep(1);
printfoo("parent :\n", fp);
exit(0);
}
在mac 上编译运行后出现如下错误:
thread 1:
, struct at 0x7000012d1ed0
foo.a = 1
foo.b = 2
foo.c = 3
foo.d = 4
parent starting second thread
thread 2: ID is 123145322045440
parent :
, struct at 0x7000012d1ed0
[1] 3990 segmentation fault ./a.out
其实在理解了pthread_exit() 和 pthread_join() 的参数关系后,就很容易看出来问题了
thr_fn1 中的 struct foo foo = {1,2,3,4}; 是在栈中申请的内存,当线程退出时也就销毁了,等到main 函数访问join 获取到的返回值 就会出现段内存错误
解决办法是将foo 作为全局变量