线程的私有数据
概述
我们知道,线程之间的数据是共享的;这时候我们就在思考,线程有时也需要有自己独有的数据,而无需与其他线程共享。于是就提出了线程的私有数据;具体实现原理而后研究补充。
相关函数
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
key:线程私有数据创建一个新键,并通过key指向新创建的键缓冲区
destructor:对应的析构函数,线程结束时自动调用
int pthread_setspecific(pthread_key_t key, const void *value);
key:线程私有数据键
value:线程私有数据值
void *pthread_getspecific(pthread_key_t key);
return:根据key,获取私有数据的值
示例代码
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_key_t key;
// 可能被线程A调用
// 也可能线程B调用
void foo()
{
char* p = (char*)pthread_getspecific(key);
printf("%s\n", p);
}
void my_malloc()
{
// 去这个线程的内存池去申请内存
void* mempool = pthread_getspecific(key);
// __my_malloc(mempool, ...);
}
void* thread_func(void* ptr)
{
// setspecific,需要在线程中调用,当然也可以在主线程中调用
// 为这个线程设置私有数据
pthread_setspecific(key, ptr);
foo();
my_malloc();
return NULL;
}
void free_func(void* ptr)
{
printf("free call\n");
free(ptr);
}
int main()
{
//int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
//key:线程私有数据键,destructor:对应的析构函数
pthread_key_create(&key, free_func);
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thread_func, strdup("thread1"));
pthread_create(&tid2, NULL, thread_func, strdup("thread2"));
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
}