线程局部变量

线程中特有的线程存储, Thread Specific Data 。
线程存储有什么用了?他是什么意思了?大家都知道,在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,
所有线程都可以使用它,改变它的值。
而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,
而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。

下面说一下线程存储的具体用法。
1) 创建一个类型为 pthread_key_t 类型的变量。

2)调用 pthread_key_create() 来创建该变量。该函数有两个参数,第一个参数就是上面声明的 pthread_key_t 变量,

第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL ,这样系统将调用默认的清理函数。

3)当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的 pthread_key_t 变量,

第二个为 void* 变量,这样你可以存储任何类型的值。

4) 如果需要取出所存储的值,调用 pthread_getspecific() 。该函数的参数为前面提到的 pthread_key_t 变量,该函数返回void * 类型的值。


下面是前面提到的函数的原型:

int pthread_setspecific(pthread_key_t key, const void *value);

void *pthread_getspecific(pthread_key_t key);

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

 

#include <malloc.h>
#include <pthread.h>
#include <stdio.h>

static pthread_key_t thread_log_key;
void write_to_thread_log (const char* message)
{
	FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
	fprintf (thread_log, "%s %d\n", message, (int)pthread_self());
}
void close_thread_log (void* thread_log)
{
	fclose ((FILE*) thread_log);
}

void* thread_function (void* args)
{
	char thread_log_filename[20];
	FILE* thread_log;
	sprintf (thread_log_filename, "thread%d.log", (int) pthread_self ());
	thread_log = fopen (thread_log_filename, "w");
	pthread_setspecific (thread_log_key, thread_log);
	write_to_thread_log (“Thread starting.”);
	/* Do work here... */
	return NULL;

}
int main ()
{
	int i;
	pthread_t threads[5];
	pthread_key_create (&thread_log_key, close_thread_log);

	for (i = 0; i < 5; ++i)
	{
		pthread_create (&(threads[i]), NULL, thread_function, NULL);
	}
	for (i = 0; i < 5; ++i)
	{
		pthread_join (threads[i], NULL);
	}
	return 0;
}  

 

另一种方法: 使用__thread关键字

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

static __thread void* ptr;

static void *thread_fn(void *arg) {
    ptr = malloc(1024);
    
    sprintf(ptr, "hello world");
    printf(">>%s(addr: %p)\n", ptr, ptr);
    
    free(ptr);
    return NULL;
}   

int main() {
    int i, n = 10; 
    pthread_t tids[10];
    for (i = 0; i < n; i++) {
        pthread_create(&tids[i], NULL, thread_fn, NULL);
    }   

    for (i = 0; i < n; i++) {
        pthread_join(tids[i], NULL);
    }   
}

 

读者可以调试一下这两个例子理解理解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值