关于apue中pthread_exit 函数的使用

本文探讨了在ApUE的线程章节中,如何正确使用pthread_exit()函数。线程退出时不应使用exit等函数,而应使用pthread_exit()或直接return。该函数的参数用于传递线程的返回值,可通过pthread_join()获取。在书中提到的一个陷阱中,由于在栈上定义的结构体foo在线程退出后被销毁,导致main函数在join时尝试访问已释放的内存,从而引发段错误。解决方法是将foo声明为全局变量。
摘要由CSDN通过智能技术生成

今天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 作为全局变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值