zoukankan      html  css  js  c++  java
  • 详解 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
    ", g++);
        pthread_exit(0) ;//pthread_exit时自动会被释放
    
    }
  • 相关阅读:
    FineUIPro v5.1.0 发布了!
    FineUI十周年纪念版即将发布(基于像素的响应式布局,独此一家)!
    FineUIPro/Mvc/Core/JS v4.2.0 发布了(老牌ASP.NET控件库,WebForms,ASP.NET MVC,Core,JavaScript)!
    选择IT公司的雇主提问
    项目管理趋势
    突发事件下的项目管理
    12-Factor与微服务
    CQRS(Command and Query Responsibility Segregation)与EventSources实例
    阅读理解力的四个层次
    2018年Code Review状态报告
  • 原文地址:https://www.cnblogs.com/zendu/p/4990756.html
Copyright © 2011-2022 走看看