免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 8433 | 回复: 3
打印 上一主题 下一主题

[函数] 关于pthread_key_create()函数的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2004-03-31 16:37 |只看该作者 |倒序浏览
int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)) ;

其中,void (*destr_function)(void *)是什么意思?
我写了这么一个程序,怎么没有看到运行这个函数。
代码如下:
#include<pthread.h>;
#include<stdio.h>;

pthread_key_t key;
void echomsg(void *t)
{
     printf("destructor excuted in thread %d, param=%d,", pthread_self(), (int *)t);
}
void *child1(void *arg)
{
     int tid = pthread_self();
     char buf[10];
     memcpy(buf, "child1", 6);
     printf("thread %d enter\n", tid);
     pthread_setspecific(key, (void*)buf);
     sleep(2);
     printf("thread %d return %s\n", tid, pthread_getspecific(key));
     sleep(2);
     pthread_exit(0);
}

void *child2(void *arg)
{
     int tid = pthread_self();
     char buf[10];
     memcpy(buf, "child2", 6);
     printf("thread %d enter\n", tid);
     pthread_setspecific(key, (void*)buf);
     sleep(2);
     printf("thread %d return %s \n", tid, pthread_getspecific(key));
     sleep(2);
     pthread_exit(0);
}

int main()
{
    int tid1,tid2;
    printf("hello\n";
    pthread_key_create(&key, (void *)echomsg);
    pthread_create(&tid1, NULL, child1, NULL);
    pthread_create(&tid2, NULL, child2, NULL);
    sleep(4);
//   pthread_key_delete(key);
    printf("main thread exit\n";
    exit(0);
}
这个程序运行的时候,看不到echomsg函数中的打印。 请那位大哥解释一下,echomsg在什么时候运行?

论坛徽章:
0
2 [报告]
发表于 2007-08-24 10:24 |只看该作者
echomsg在每个线程调用pthread_exit()后被调用.
===========
我的理解.

论坛徽章:
0
3 [报告]
发表于 2007-08-24 10:45 |只看该作者
以后你把你的代码加上CODE吧不然要是长的代码估计不会有太多人看,你这个问题你可以延长main函数中的sleep(4)比如改成10或者20应该可以打印出来或者直接把sleep出掉换成
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);

论坛徽章:
0
4 [报告]
发表于 2007-08-24 11:18 |只看该作者
void echomsg(void *t)
{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf("destructor excuted in thread %d, param=%d,", pthread_self(), (int *)t);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fflush();
}

另外,主线程还得有pthread_join.
要么是因为buffered io的原因,要么是因为线程根本没执行。

[ 本帖最后由 dzbjet 于 2007-8-24 11:20 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP