【Linux】 线程

pthread_join: 获取线程返回值 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

/**
 * 测试 pthread_join
 * 阻塞等待一个子线程的退出,可以接收到某一个子线程调用pthread_exit时设置的退出状态值
 */

void *tfun1(void *arg)
{

    //static int num =666;  return (void*) &num;
    
    //char buf[32]=(char*)malloc(sizeof(buf)); //error 数组名是一个常量
    char *buf =(char*) malloc(100*sizeof(char));
    strcpy(buf,"hello world");




    // int *a=(int *)malloc(sizeof(int));
    // *a=110; return (void*)a; //不要返回一个局部变量,局部变量是线程私有的,它只在当前线程的当前函数栈帧中有效

    printf("thread-son is running\n");

    sleep(3);

    printf("the thread-son will quit\n");

    return (void *)buf;
    
}

int main(int argc, char const *argv[])
{
    printf("main-thread is Runing\n");
    pthread_t thread;

    if (pthread_create(&thread, NULL, tfun1, NULL) != 0)
    {
        perror("fail to pthread_create");
        exit(1);
    }

    // 通过调用pthread_join函数阻塞等待子线程退出
   // int *rtv;
   char * rtv;
    if (pthread_join(thread, (void **)&rtv) != 0)
    {
        perror("fail to pthread_join");
        exit(-1);
    }

   // printf("rtval =%d\n", *rtv);
        printf("rtval =%s\n", rtv);

    printf("进程要退出了\n");
    return 0;
}

pthread_detach:

功能:使调用线程与当前进程分离,使其成为一个独立的线程,
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>



void * thread_fun(void * arg){
printf("子线程正在运行\n");
sleep(3);
printf("子线程要退出了\n");
}

int main(int argc, char const *argv[])
{
printf("主控线程正在执行\n");

pthread_t thread;

if(pthread_create(&thread, NULL, thread_fun, NULL) != 0)
 {
 perror("fail to pthread_create");
 exit(1);
 }


//通过pthread_detach函数将子线程设置为分离态,既不用阻塞,也可以自动回收子线程退出的资源

if(pthread_detach(thread)!=0){
    perror("fail to pthread_detach");
     exit(1);
}
//如果原本子线程是结合态,需要通过pthrad_join函数回收子线程退出的资源,
//但是这个函数是一个阻塞函数,如果子线程不退出,就会导致当前进程(主控线程)
//无法继续执行,大大的限制了代码的运行效率
//如果子线程已经设置为分离态,就不需要再使用pthread_join了


while(1) //detach 模式下,子线程即使不结束,也不影响main的执行
{
 printf("hello world\n");
 sleep(1);
 }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值