zoukankan      html  css  js  c++  java
  • pthreads之joinable和detach函数

    Joinable and Detached Threads

    http://www.domaigne.com/blog/computing/joinable-and-detached-threads/

    Introduction

    By default, created threads are joinable. That means, we can wait for its completion in any other thread using the function pthread_join():

    #include 
    
    int pthread_join(
        pthread_t thread, // thread to join
        void **value_ptr  // store value returned by thread
    );
    

    This function shall suspend the calling thread until the targeted thread terminates. When value_ptr is non-NULL, then value_ptr shall contain the value
    returned by thread. We saw how to use pthread_join() already in our article Pthreads argument passing.

    Joinable Thread and Consequences

    A thread may have already terminated before we join it. As a result, the Pthreads system must retain some information when a thread is joinable: namely, at least the thread ID and the returned value[1]. Indeed this information is needed for joining the thread.

    Actually, the Pthreads system can retain also other resources associated with the joinable thread, like for instance the thread’s stack. This is perfectly legal from a POSIX standpoint. In fact, pthread_join() guarantees to reclaim whatever storage is associated to the joined thread.

    Detached Threads

    What should I do when my thread doesn’t return anything useful, and I don’t have to wait for its completion? Do I have to call pthread_join() anyway just for clean-up purpose?

    Fortunately, not. Pthreads offers a mechanism to tell the system: I am starting this thread, but I am not interested about joining it. Please perform any clean-up action for me, once the thread has terminated. This operation is called detaching a thread. We can detach a thread as follows:

    • During thread creation using the detachstate thread attribute.
    • From any thread, using pthread_detach().

    Let’s start with the second form, which is the easiest.

    #include 
    
    int pthread_detach(
        pthread_t thread, // thread to detach
    );
    
  • 相关阅读:
    用三张图宏观把握数据库
    MySQL数据库安装与配置详解(图文)
    如何彻底的删除MySQL数据库(图文教程)
    几个常用网络/服务器监控开源软件
    tomcat服务器虚拟目录的映射方式
    手动开发动态资源之servlet初步
    软件项目开发没规划好就注定会失败
    在系统设计中,如何控制层次的问题
    软件系统架构中的分层思想
    鸟哥谈PHP的架构与未来发展
  • 原文地址:https://www.cnblogs.com/CreatorKou/p/8552340.html
Copyright © 2011-2022 走看看