博客
关于我
线程的退出
阅读量: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 module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node exporter完整版
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node 裁切图片的方法
    查看>>
    Node+Express连接mysql实现增删改查
    查看>>
    node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
    查看>>