博客
关于我
线程的退出
阅读量: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/

    你可能感兴趣的文章
    NT symbols are incorrect, please fix symbols
    查看>>
    ntko web firefox跨浏览器插件_深度比较:2019年6个最好的跨浏览器测试工具
    查看>>
    ntko文件存取错误_苹果推送 macOS 10.15.4:iCloud 云盘文件夹共享终于来了
    查看>>
    ntpdate 通过外网同步时间
    查看>>
    NTP配置
    查看>>
    Nuget~管理自己的包包
    查看>>
    nullnullHuge Pages
    查看>>
    Numix Core 开源项目教程
    查看>>
    NumPy 或 Pandas:将数组类型保持为整数,同时具有 NaN 值
    查看>>
    numpy 数组 dtype 在 Windows 10 64 位机器中默认为 int32
    查看>>
    numpy 用法
    查看>>
    Numpy 科学计算库详解
    查看>>
    Numpy.ndarray对象不可调用
    查看>>
    Numpy如何使用np.umprod重写range函数中i的python
    查看>>
    numpy数组索引-ChatGPT4o作答
    查看>>
    numpy转PIL 报错TypeError: Cannot handle this data type
    查看>>
    NUUO网络视频录像机 css_parser.php 任意文件读取漏洞复现
    查看>>
    oauth2-shiro 添加 redis 实现版本
    查看>>
    OAuth2.0_JWT令牌-生成令牌和校验令牌_Spring Security OAuth2.0认证授权---springcloud工作笔记148
    查看>>
    OAuth2.0_JWT令牌介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记147
    查看>>