博客
关于我
线程的退出
阅读量:320 次
发布时间:2019-03-04

本文共 1030 字,大约阅读时间需要 3 分钟。

线程退出函数

在线程编程中,线程退出是一个重要的操作。 Linux 系统使用 pthread_exit 函数来退出线程。需要注意的是,exit 函数用于退出整个进程,而 return 语句则用于主控线程,代表程序退出。

在线程中使用 pthread_exit 时,需注意以下几点:

  • pthread_exit 会释放线程所持有的资源
  • 子线程退出后,父线程会继续执行
  • 线程退出后,线程的属性可能会被系统回收
  • 示例代码分析

    #include 
    #include
    #include
    #include
    void* thr(void *arg) { printf("I am a thread! pid=%d,tid=%lu\n", getpid(), pthread_self()); // 由于 pthread_exit 不会返回值,建议不要使用 return pthread_exit(NULL); exit(1); // 这里会导致整个进程退出}int main() { pthread_t tid; pthread_create(&tid, NULL, thr, NULL); printf("I am a main thread! pid=%d,tid=%lu\n", getpid(), pthread_self()); sleep(3); printf("I will out\n"); pthread_exit(NULL); // 父线程退出,子线程也会跟着退出 return 0;}
    • 父线程 (main) 创建子线程后,通过 sleep(3) 给予子线程执行时间。
    • 当父线程调用 pthread_exit 时,子线程也会被终止,并打印相关信息。
    • 两个线程都会输出其 PID 和 TID 信息,子线程会在父线程退出后跟随退出。

    注意事项总结

  • pthread_exit 适用于线程退出,而 exit 适用于进程退出。
  • 在线程中使用 return 会导致线程返回到父线程,并可能影响线程的退出状态。
  • 子线程退出后,父线程会继续执行剩余的逻辑。
  • 线程退出时,不要使用 return,除非你清楚这是一个主控线程。
  • 通过上述分析,我们可以清晰地看到线程退出函数的使用方法及其注意事项。

    转载地址:http://lrwh.baihongyu.com/

    你可能感兴趣的文章
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
    查看>>
    ORCHARD 是什么?
    查看>>
    Struts2中使用Session的两种方法
    查看>>
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>