线程存储函数的使用

线程存储函数的使用比较简单,这里只记录一下用例代码:

<pre name="code" class="cpp">#include <gmock/gmock.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string>

class ThreadLocalTest : public testing::Test
{
public:
	void SetUp(){}
	void TearDown(){}
};

struct Person
{
	int age;
	std::string name;
};

pthread_key_t key;

void *func1(void* arg)
{
	#if 0
	{
		///< 在此作用域内创建的线程存储对象,外面无法访问
		Person bobo;
		bobo.age = 23;
		bobo.name = "bobo";
		pthread_setspecific(key, &bobo);
		printf("func1 person address : %p\n", &bobo);
	}
	///< 覆盖 bobo 对象占用的内存
	Person test;
	#endif
	Person bobo;
	bobo.age = 23;
	bobo.name = "bobo";
	pthread_setspecific(key, &bobo);
	printf("func1 person address : %p\n", &bobo);
		
	printf("func1 thread local person address : %p\n", (Person*)pthread_getspecific(key));
	printf("func1 person age : %d, person name : %s\n", ((Person*)pthread_getspecific(key))->age, 
		((Person*)pthread_getspecific(key))->name.c_str());
	return NULL;
}

void *func2(void* arg)
{
	Person huihui;
	huihui.age = 24;
	huihui.name = "huihui";
	pthread_setspecific(key, &huihui);
	printf("func2 person address : %p\n", &huihui);
	printf("func2 thread local person address : %p\n", (Person*)pthread_getspecific(key));
	printf("func2 person age : %d, person name : %s\n", ((Person*)pthread_getspecific(key))->age, 
		((Person*)pthread_getspecific(key))->name.c_str());
	return NULL;
}

TEST_F(ThreadLocalTest, ThreadLocalTestOne)
{
	pthread_t t1, t2;
	pthread_key_create(&key, NULL);
	pthread_create(&t1, NULL, &func1, NULL);
	pthread_create(&t2, NULL, &func2, NULL);
	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	pthread_key_delete(key);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值