关于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时自动会被释放

}      

posted on 2012-06-25 20:12  很多不懂呀。。  阅读(12804)  评论(0编辑  收藏  举报

导航