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

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    Node.js 文件系统的各种用法和常见场景
    查看>>
    node.js 配置首页打开页面
    查看>>
    node.js+react写的一个登录注册 demo测试
    查看>>
    Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
    查看>>
    nodejs libararies
    查看>>
    nodejs-mime类型
    查看>>
    nodejs中Express 路由统一设置缓存的小技巧
    查看>>
    Node入门之创建第一个HelloNode
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm和yarn的使用对比
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>