当前位置: 首页 > article >正文

【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;
}


http://www.kler.cn/news/137074.html

相关文章:

  • 《PP-OCRv1》论文精读:PaddleOCR是目前SOTA级别的OCR开源技术(截止2024年10月)
  • 删除本地文件不影响Github
  • 单片机输出方波
  • 【算法系列-栈与队列】匹配消除系列
  • 如何在算家云搭建GPT-SOVITS(语音转换)
  • 深度学习的关键概念和术语
  • CSS中常用的伪元素选择器
  • 机器学习第11天:降维
  • 场景中的解剖学方向标记_vtkAnnotatedCubeActor
  • 外贸干货|深度剖析外贸出口各国操作细节
  • 每日一题 2216. 美化数组的最少删除数(中等,贪心)
  • Foodpanda API连接的艺术:无代码开发如何集成营销系统和广告推广工具
  • 每日一练 | 华为认证真题练习Day134
  • SQL基础理论篇(七):多表关联的连接算法
  • 『亚马逊云科技产品测评』活动征文|借助AWS EC2搭建服务器群组运维系统Zabbix+spug
  • 软考高项知识点 安全技术
  • 【Linux】指令详解(二)
  • 如何将MBR转换为GPT?原来操作这么简单!
  • milvus数据库搜索
  • 隐私计算迎来千亿级风口,一文讲清它的技术理论基础
  • STM32 -Bin/Hex文件格式解析
  • 【excel技巧】单元格内的公式如何隐藏?
  • APP分发平台指的是将开发完成的应用程序
  • 数据仓库相关
  • 适合学校或高校老师、学生学习用的网盘推荐
  • Modbus TCP/RTU协议转PROFINET协议网关