多线程编程3

线程清理处理函数:
void pthread_cleanup_push(void (*rtn)(void *), void *arg );
设置清理函数
void pthread_cleanup_pop(int execute);
execute为0,清理函数将不被调用;不为0则调用
清理函数运行的三种情况:
1,调用pthread_exit时
2,响应取消请求时
3,用非0 execute参数调用pthread_cleanup_pop时
(不包括return!)
pthread_cleanup_push与pthread_cleanup_pop调用应匹配(由此产生以下令我不解的程序问题)

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

void CleanUp( void *arg )
{
      printf( "cleanup %s\n", (char *)arg );
}

void *Thr1( void *arg )
{
      pthread_cleanup_push( CleanUp, "thread 1 cleanup done\n" );
      printf( "thread 1 push done\n" );
      if( arg )
            pthread_exit( (void *)2 );
      else
            return ( (void *)1 );
      pthread_cleanup_pop( 0 );
}
void *Thr2( void *arg )
{
      pthread_cleanup_push( CleanUp, "thread 1 cleanup done\n" );
      printf( "thread 1 push done\n" );
     if( arg );
        pthread_cleanup_pop( 0 );
    else
        pthread_cleanup_pop( 1 )
;
      pthread_exit( (void *)2 );
}
int main( int argc, char **argv )
{
      pthread_t      tid1, tid2, tid3, tid4;
      void       *tret;

      pthread_create( &tid1, NULL, Thr1, (void *)0 );//相同的函数Thr1
      pthread_create( &tid2, NULL, Thr1, (void *)1 );
      pthread_create( &tid3, NULL, Thr2, (void *)0 );
      pthread_create( &tid4, NULL, Thr2, (void *)1 );
      pthread_join( tid1, &tret );
      pthread_join( tid2, &tret );
      pthread_join( tid3, &tret );
      pthread_join( tid4, &tret );

      exit( 0 );

}
程序编译不通过,出错原因是Thr2中if语句那一部分有问题,但是从push和pop要匹配使用的要求来看,Thr2的却只会执行pthread_cleanup_pop( 0 );或者pthread_cleanup_pop( 1 );那为什么会出错呢?
把出错部分删除则编译通过,也认识到了:
创建的不同线程可以对应相同的函数


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值