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;}

只有不断找寻机会的人才会及时把握机会。

Linux私有数据编程

相关文章:

你感兴趣的文章:

标签云: