Chinaunix首页 | 论坛 | 博客
  • 博客访问: 446717
  • 博文数量: 145
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1060
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-22 11:52
个人简介

专注计算机技术: Linux Android 云计算 虚拟化 网络

文章分类

全部博文(145)

文章存档

2016年(3)

2015年(21)

2014年(75)

2013年(46)

我的朋友

分类: LINUX

2015-01-12 17:25:06

使用Linux的线程时,你可能会疑惑,我在线程函数调用pthread_exit后,是不是已经高枕无忧,不存在资源泄漏了呢? 以下将会给出答案。 

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_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
#include
#include
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时自动会被释放
}     

 

阅读(4724) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

COMPUTER-TECH2015-01-12 17:26:38

pthread_join一般是主线程来调用,用来等待子线程退出,因为是等待,所以是阻塞的,一般主线程会依次join所有它创建的子线程。
pthread_exit一般是子线程调用,用来结束当前线程。子线程可以通过pthread_exit传递一个返回值,而主线程通过pthread_join获得该返回值,从而判断该子线程的退出是正常还是异常。