您的位置:首页 > 移动开发 > 微信开发

线程特定数据的小程序。

2011-08-18 22:27 155 查看
thread-specific data是为了解决一个线程想用全局变量来实现某个目的却因为多个线程之间不能很好的共享全局变量(这里里面牵涉到同步问题,because multiple threads cannot use the buffer to hold different things at the same time .)。我还有一点没想明白,同一个进程的线程之间是如何共享数据的?不适用thread-specific data ?好像thread-specific data又说“这种方式可以较好的实现一个线程使用唯一的(别的线程都不知道的)全局变量,这

#include    <pthread.h>
#include    <string.h>
#include    <stdlib.h>
#include    <stdio.h>

#define     LEN     100
pthread_key_t       key;

void A(char *s){
char *str = (char *) pthread_getspecific(key);
printf("Address:%d", pthread_getspecific(key));
strncpy(str, s, LEN);
}

void B( ){
char *str = (char *) pthread_getspecific(key);
printf("Address:%d", pthread_getspecific(key));
printf("%s\n", str);
}

void destructor( void *ptr){
free(ptr);
printf("memory freed\n");
}

void *threadfunc1(void *pvoid){
pthread_setspecific(key, malloc(LEN));
A("Thread1");
B();
}

void *threadfunc2(void *pvoid){
pthread_setspecific(key, malloc(LEN));
A("Thread2");
B();
}

int
main()
{
pthread_t   tid1, tid2;
pthread_key_create(&key, destructor);

pthread_create(&tid1, NULL, &threadfunc1, NULL);
pthread_create(&tid2, NULL, &threadfunc2, NULL);

pthread_exit(NULL);
return 0;
}

这个程序中,函数A和函数B共享了一个 内存区,而这个内存区是特定于调用A和B线程的。对于其他线程,这个内存区是不可见的,这就安全有效的达到了线程中的各个函数之间共享数据的目的。

哦,终于看明白了,共享数据是对于线程中的各个函数而言的。不是对于不同线程间而言的。不同线程间共享数据是不是用的thread-specific data这个方式的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: