Chinaunix首页 | 论坛 | 博客
  • 博客访问: 581292
  • 博文数量: 353
  • 博客积分: 1104
  • 博客等级: 少尉
  • 技术积分: 1457
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-23 23:02
个人简介

1、刚工作时做Linux 流控;后来做安全操作系统;再后来做操作系统加固;现在做TCP 加速。唉!没离开过类Unix!!!但是水平有限。。

文章存档

2015年(80)

2013年(4)

2012年(90)

2011年(177)

2010年(1)

2009年(1)

分类: LINUX

2011-10-24 13:52:46

pthread_detach等函数与线程创建实例  
今天实验了Linux下的线程清理处理程序,原来以为比较简单,很快就能完成。但是第一次做,过程中却发生了几个问题,好在都一一解决了,现将代码贴在下面。

2




#include
#include
#include
#include

void exe_exit1(void *arg)
{
    printf("我是线程退出时要执行的程序1!");
    printf("传递给我的参数是:%s\n",(char *)arg);
}

void exe_exit2(void *arg)
{
    printf("我是线程退出时要执行的程序2!");
    printf("传递给我的参数是:%s\n",(char *)arg);
}

void *func()
{
    int ret;
   
    ret=pthread_detach(pthread_self());
    if(ret==0)
        printf("pthread_detach调用成功!\n");
    else
        printf("pthread_detach调用出错,错误编号:%d",ret,errno);
       
    printf("我是线程,已经开始启动!\n");
    pthread_cleanup_push(exe_exit2,"给exe_exit2的参数");
    pthread_cleanup_push(exe_exit1,"给exe_exit1的参数");
    printf("pthread_cleanup_push设置完成。\n");
    printf("我是线程,即将退出。\n");
    pthread_exit((void *)0);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
//    printf("pthread_cleanup_pop设置完成。\n");
}

int main()
{
    int ret;
    pthread_t tid;
   
    pthread_create(&tid,NULL,func,NULL);
   
    sleep(2);
    exit(0);
}

编译: gcc -o pthread_exit -lpthread pthread_exit.c
执行: ./pthread_exit

///////////////////////////////// 运行结果 //////////////////////////////////
pthread_detach调用成功!
我是线程,已经开始启动!
pthread_cleanup_push设置完成。
我是线程,即将退出。
我是线程退出时要执行的程序1!传递给我的参数是:给exe_exit1的参数
我是线程退出时要执行的程序2!传递给我的参数是:给exe_exit2的参数

=============================

几个需要说明的地方:

1、pthread_cleanup_pop的参数是0的话,表示不执行线程清理处理程序(但并不妨碍把栈顶存放的那个处理程序的记录弹出,只是不执行而已),即这里的exe_exit1和exe_exit2。因此,如果程序中的这一句pthread_exit((void *)0);移到func函数结尾的话,exe_exit1和exe_exit2函数将不会得到执行,因为之前的两个pthread_cleanup_pop函数已经把存储的处理程序的记录给清空了。再执行到pthread_exit((void *)0);的时候栈中已经没有待执行的处理函数了。

2、虽然本程序中的pthread_cleanup_pop函数的参数是0,这两句本身不会触发线程清理处理程序(触发线程清理处理程序的任务是由pthread_exit来完成的)。但是这两句不能去掉,可以试一下把这两句注释掉,再编译的话就会出现错误。原因估计应该是pthread_cleanup_pop必须要和pthread_cleanup_push成对出现吧。

3、我一开始把pthread_detach函数放在了main函数中,结果运行时总是提示Segmentation fault(段错误)。后来在网上搜索后,改为把pthread_detach函数在func函数中调用,问题解决。
阅读(675) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~