线程存储函数的使用

来源:互联网 发布:cad迷你看图mac版免费 编辑:程序博客网 时间:2024/06/05 21:10

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

<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;#endifPerson 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);}

0 0