pthread_key的使用

背景

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

int global_sum = 0;

void * mul_add(void *arges)
{
	for(int i=0; i<100; i++)
	{
		global_sum += 1;
	}
    return 0;
}

int main()
{
	pthread_t t1;
	pthread_t t2;

	pthread_create(&t1, NULL, mul_add, NULL);
	pthread_create(&t2, NULL, mul_add, NULL);

	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
}

        上面的代码中global_sum的值时候到两个线程影响的。有时候希望,同一个函数访问一个各个线程自己的全局变量,而不用为每个线程单独定义一个全局变量。这个时候pthread_key就很好地解决了这个问题。

api

        pthread_key_create,pthread_setspecific,pthread_getspecific

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

pthread_key_t global_sum_key;

void mul_add()
{
	int * global_sum = (int *)pthread_getspecific(global_sum_key);
	for(int i=0; i<100; i++)
	{
		*global_sum += 1;
	}

	printf("global_sum:%d!\n", *global_sum);
}

void * mul_fun(void * args)
{
	void * global_sum = calloc(1, sizeof(int));
	pthread_setspecific(global_sum_key, global_sum);
	mul_add();
    return NULL;
}

void global_sum_free(void * des)
{
	free(des);
}

int main()
{
	pthread_t t1;
	pthread_t t2;

	pthread_key_create(&global_sum_key, global_sum_free);

	pthread_create(&t1, NULL, mul_fun, NULL);
	pthread_create(&t2, NULL, mul_fun, NULL);

	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
}

        上面的代码两个线程都打印了100。证明了各自的global_sum_key空间里面的值是不受影响的。这样子就好像函数都用global_sum_key这个全局变量,但是这个全局变量是各自线程独立的。

        

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值