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

pthread_detach函数

pthread_join函数用于连接线程,阻塞等待某个线程结束,线程结束后回收线程资源,线程在创建后就在连接状态,只有可连接的函数才能被连接到。创建线程后,如果没有使用pthread_join,线程结束后资源无法回收,线程就会成为僵尸。 pthread_detach用于分离线程,分离后的线程会自己释放资源不会成为僵尸。

include <pthread.h>
#include <stdio.h>
#include <unistd.h>#define N 10void* thread_fun_0(void* arg) {for (int i = 0; i < N; ++i) {printf("thread_fun_0[%d]\n",i);sleep(1);}pthread_exit((void *)("thread_fun_0"));  
}void* thread_fun_1(void* arg) {for (int i = 0; i < N; ++i) {printf("thread_fun_1[%d]\n",i);sleep(1);}pthread_exit((void *)("thread_fun_1"));  
}
int main() {pthread_t tid_0, tid_1;printf("main beign\n");pthread_create(&tid_0, NULL, thread_fun_0, NULL);pthread_create(&tid_1, NULL, thread_fun_1, NULL);void *thread_fun_0_r;void *thread_fun_1_r;int result_0 = pthread_join(tid_0,  &thread_fun_0_r);int result_1 = pthread_join(tid_1,  &thread_fun_1_r);printf("result_0:%d,thread_fun_0_r:%s\n",result_0,(char*)thread_fun_0_r);printf("result_1:%d,thread_fun_1_r:%s\n",result_1,(char*)thread_fun_1_r);printf("main end\n");pthread_exit(NULL);  
}

在这里插入图片描述
.在主线使用 pthread_join函数,获得了线程的返回结果。如果在线程中使用pthread_detach函数分离线程。如果分离后使用pthread_join函数就无效。

在这里插入图片描述

 使用pthread_detach( thread_self() )与pthread_detach( tid_0);pthread_join就无法阻塞并且获取线程返回值,pthread_join函数返回值是22.即EINVAL,
http://www.xdnf.cn/news/20450.html

相关文章:

  • 2025最新超详细FreeRTOS入门教程:第二章 FreeRTOS任务创建
  • 设计一个 AB 测试平台
  • 实例和对象的区别
  • 【目录-单选】鸿蒙HarmonyOS开发者基础
  • 自适应滤波器:Ch4 最小均方(LMS)算法
  • [光学原理与应用-433]:晶体光学 - 晶体光学是研究光在单晶体中传播规律及其伴随现象的分支学科,聚焦于各向异性光学媒质的光学特性
  • 上海“我店”模式:消费增值新玩法及其隐忧
  • 论文阅读:VGGT Visual Geometry Grounded Transformer
  • 【C++】引用的本质与高效应用
  • 【高等数学】第十一章 曲线积分与曲面积分——第三节 格林公式及其应用
  • javascript 国际化方法
  • AI 生成式艺术重塑动漫角色创作:从技术逻辑到多元可能性(一)
  • GPT-5发布:统一智能体时代的开启——从“工具”到“协作者”的范式跃迁
  • 详解MySQL环境变量配置及其在备份中的应用
  • 计算机内存的工作原理
  • 打工人日报#20250906
  • 模电仿真软件:MultSim14.3下载与安装
  • 【面板数据】各省制造业出口技术复杂度数据集(2010-2023年)
  • AP1271:高性能低功耗LDO稳压器,为精密电子设备提供稳定动力
  • python graphviz中文测试
  • queue容器的常用函数 和注意事项
  • windows server 2022安装终端
  • 计算机视觉(八):开运算和闭运算
  • C++:深入剖析vector
  • 数字化赋能全球扩张:名创优品携手巨益科技的信息化转型深度实践
  • 【开题答辩全过程】以 哈尔滨裕丰草莓园管理系统为例,包含答辩的问题和答案
  • JVM中常见的GC垃圾收集器
  • OpenCV 实战篇——如何测算出任一副图片中的物体的实际尺寸?传感器尺寸与像元尺寸的关系?
  • SQL 进阶指南:视图的创建与使用(视图语法 / 作用 / 权限控制)
  • Obsidian: 图片本地化插件-Local Images Plus与图片重命名插件-Paste Image Rename使用说明