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

    你可能感兴趣的文章
    ORM框架 和 面向对象编程
    查看>>
    OS X Yosemite中VMware Fusion实验环境的虚拟机文件位置备忘
    查看>>
    os.environ 没有设置环境变量
    查看>>
    os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
    查看>>
    os.removexattr 的 Python 文档——‘*‘(星号)参数是什么意思?
    查看>>
    os.system 在 Python 中不起作用
    查看>>
    OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
    查看>>
    OSCACHE介绍
    查看>>
    SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
    查看>>
    OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
    查看>>
    SQL--mysql索引
    查看>>
    OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
    查看>>
    OSChina 周日乱弹 —— 2014 年各种奇葩评论集合
    查看>>
    OSChina 技术周刊第十期,每周技术抢先看!
    查看>>
    oscp--python
    查看>>
    OSError: no library called “cairo-2“ was foundno library called “cairo“ was foundno library called
    查看>>
    OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
    查看>>
    osgearth介绍
    查看>>
    OSGi与Maven、Eclipse PlugIn的区别
    查看>>
    Osgi环境配置
    查看>>