关于pthread_cleanup_push() …

            linux系统中提供了一对函数 :pthread_cleanup_push( ) 和 pthread_cleanup_pop( ) 用于自动释放资源 , 就像释放锁,以防其它线程永远都无法得到锁,而造成死锁.从 pthread_cleanup_push( ) 的调用点到pthread_cleanup_pop ( )之间的程序段中的终止动作(如调用 pthread_exit ) 都将执行 pthread_cleanup_push ( ) 所指定的清理函数. 并且这两个函数都是以宏的形式提供的:
              # include
              #define   pthread_cleanup_push ( routine, arg)
              {
                    struct   _pthread_cleanup_buffer     buffer;
                    _pthread_cleanup_push (&buffer, (routine) ,(srg));
              #define   pthread_cleanup_pop
                    _pthread_cleanup_pop (&buffer, (exeute));
                }
         
            因为 pthread_cleanup_push( ) 带有一个" { ", 而 pthread_cleanup_pop ( ) 带有一个 " } ",因此这两个函数必须成对出现, 且必须位于程序的同一代码段中才能通过编译. pthread_clean_up ( )函数执行压栈清理函数的操作 , pthread_cleanup_pop ( )函数执行从栈中删除清理函数的操作.
           
          pthread_cleanup_push ( ) 和 pthread_cleanup_pop ( ) 函数采用先入后出的栈结构管理 ,void routine (  void  * arg)函数在调用 pthread_cleanup_push ( )时压入清理函数栈 ,多次对 pthread_cleanup_push ( ) 的调用将在清理函数栈中形成一个函数链 ,在执行该函数链时按照压栈的相反顺序弹出 . execute参数表示执行到pthread_cleanup_pop ( )时是否在弹出清理函数的同时执行该函数   , 为0表示不执行, 非0为执行 . 这个参数并不影响异常终止时清理函数的执行.

在以下三种情况下 , pthread_cleanup_pop ( )压栈的"清理函数" 会被调用:
1 . 线程调用 pthread_exit ( )函数 , 而不是直接 return .
2. 响应取消请求时,也就是有其它的线程对该线程调用 pthread_cancel ( ) 函数 . 
3. 调用 pthread_cleanup_pop ( )时,其参数非零 . 

注意:
1. 当 pthread_cleanup_pop ( )的参数为0 时,仅仅在线程调用thread_exit ( )函数时或者其它线程对本线程调用
     pthread_cancel ( )函数时 , 才在弹出  "清理函数" 的时候并同时执行该 "清理函数" .
2 . 注意 pthread_exit ( )终止线程与线程直接return终止线程的区别 , 调用return是不会在弹出 " 清理函数" 的同时并执行该 " 清理函数" 的 . 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值