Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

线程与私有数据示例

Posted on 2009-07-05 14:27 Prayer 阅读(188) 评论(0)  编辑 收藏 引用 所属分类: LINUX/UNIX/AIX
#include <stdio.h>
#include <pthread.h>

pthread_key_t    key;
void echomsg(char *s)
{
    printf("thread auto free private varible %s\n",s);
    free(s);
    s = NULL;
}

void * child1(void *arg)
{
    //int tid = pthread_self();
    char * str = (char*)malloc(20);
    memset(str,0,20);
    sprintf(str,"%s","thread child1");
    printf("thread %s enter\n",str);
    pthread_setspecific(key,(void*)str);
    sleep(2);
    //printf("thread %d returns %d\n",tid,pthread_getspecific(key));
    sleep(5);
}

void * child2(void * arg)
{
    //int tid = pthread_self();
    char * str = (char*)malloc(20);
    memset(str,0,20);
    sprintf(str,"%s","thread child2");
    printf("thread %s enter \n",str);
    pthread_setspecific(key,(void*)str);
    sleep(1);
    //printf("thread %d returns %d\n",tid,pthread_getspecific(key));
    sleep(5);
}

int main(void)
{
    int tid1,tid2;
    printf("hello\n");
    pthread_key_create((pthread_key_t*)&key,(void*)echomsg);
    pthread_create((pthread_t*)&tid1,NULL,child1,NULL);
    pthread_create((pthread_t*)&tid2,NULL,child2,NULL);
    sleep(10);
    pthread_key_delete(key);
    return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理