旅途

如果想飞得高,就该把地平线忘掉

Linux私有数据编程

  在单线程程序中,经常要用全局变量实现共享数据。在多线程环境下,由于数据空间是共享的,因此全局变量也是各线程共有。但有时在应用程序设计过程中有必要 提供线程私有的全局变量,仅在某个线程中有效,却可以跨多个函数进行访问,比如程序可能需要每个线程维护一个链表,要使用相同的函数操作,最简单的办法就 是使用同名而不同变量地址的线程相关数据结构。这样的数据结构就是私有数据(TSD)
   
    程序就是演示这样的数据结构。创建了两个新的线程,分别把自己的ID写入私有数据,然后互不干扰的输出。代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
 
pthread_key_t key;
 
void echomsg(int t)
{
 printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);   
 
}

void child()
{
 int tid;
 
 tid = pthread_self(); 
   printf("thread %d enter\n",tid);
 sleep(1);
   pthread_setspecific(key,(void *)tid);
   printf("thread %d returns %d\n",tid,pthread_getspecific(key));
 sleep(1);
}

int main()
{
 pthread_t tid1,tid2;
 
   printf("Hello\n");
  
   pthread_key_create(&key,(void *)echomsg);
   pthread_create(&tid1,NULL,(void *)child,NULL);
   pthread_create(&tid2,NULL,(void *)child,NULL);
  
   pthread_join(tid1,NULL);
 pthread_join(tid2,NULL);
   pthread_key_delete(key);
  
   printf("main thread exit\n");  
   return 0;
}

posted on 2007-08-11 01:47 旅途 阅读(305) 评论(0)  编辑 收藏 引用 所属分类: Linux开发


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