關於pthread_detach( )


man pthread_detach 

 

pthread_t  

類型定義: typedef unsigned long int pthread_t;   //come from /usr/include/bits/pthread.h

用途:pthread_t用於聲明線程ID。  sizeof (pthread_t) =4;

   linux線程執行和windows不同,pthread有兩種狀態joinable狀態和unjoinable狀態

 一個線程默認的狀態是joinable,如果線程是joinable狀態,當線程函數自己返回退出時或pthread_exit時都不會釋放線程所占用堆棧和線程描述符(總計8K多)。只有當你調用了pthread_join之后這些資源才會被釋放。
若是unjoinable狀態的線程,這些資源在線程函數退出時或pthread_exit時自動會被釋放。

unjoinable屬性可以在pthread_create時指定,或在線程創建后在線程中pthread_detach自己, 如:pthread_detach(pthread_self()),將狀態改為unjoinable狀態,確保資源的釋放。如果線程狀態為 joinable,需要在之后適時調用pthread_join.
 

pthread_self()函數用來獲取當前調用該函數的線程的線程ID
NAME
       pthread_self - get the calling thread ID

SYNOPSIS
       #include <pthread.h>

       pthread_t pthread_self(void);

DESCRIPTION
       The pthread_self() function shall return the thread ID of the calling thread.

RETURN VALUE
       Refer to the DESCRIPTION.

ERRORS
       No errors are defined.

       The pthread_self() function shall not return an error code of [EINTR].

       The following sections are informative.

 

/*example:test.c*/

#include<pthread.h>
#include<stdio.h>
#include<unistd.h>

void print_message( void *ptr );

int main( int argc, char *argv[] )
{
                        pthread_t thread_id; 
                         while( 1 )
                        {
                                        pthread_create( &thread_id, NULL, (void *)print_message, (void *)NULL );// 一個線程默認的狀態是joinable

                        }

                        return 0;
}

void  print_message( void *ptr )
{
                pthread_detach(pthread_self());//pthread_detach(pthread_self()),將狀態改為unjoinable狀態,確保資源的釋放
                static int g;
                printf("%d\n", g++);
                pthread_exit(0) ;//pthread_exit時自動會被釋放

}      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM