1.线程局部存储
1.1 概述
线程局部存储能够将一个变量分为多份,每个线程可以使用属于自己的一份,也就是说:A线程对该数据处理的结果并不会影响B线程中的该数据。
1.2 API介绍
#include <pthread.h>
/**
* key:线程局部存储变量key值:
* void (*destructor)(void*):函数指针,用来释放线程局部存储变量
*/
int pthread_key_create(pthread_key_t* key, void (*destructor)(void*));
int pthread_key_delete(pthread_key_t key);
int pthread_setspecific(pthread_key_t key, const void* value);
void* pthread_getspecific(pthread_key_t key);
__thread int val = 0;
pthread_key_create
: 创建线程局部存储key对象,同时指定线程局部存储变量释放函数。pthread_key_create
:用来删除线程局部存储key对象。pthread_setspecific
:先key对象指向的区域设置线程局部存储变量。pthread_getspecific
:从key对象指向的区域获取线程局部存储变量。__thread
:可以直接定义一个线程局部存储变量,非常简单。1.3 实例
```cppinclude
include
include
//线程局部存储key pthread_key_t thread_log_key;
void write_to_thread_log(const char* message) { if (message == NULL) return;
FILE* logfile = (FILE*)pthread_getspecific(thread_log_key);
fprintf(logfile, "%s\n", message);
fflush(logfile);
}
void close_thread_log(void* logfile) { char logfilename[128]; sprintf(logfilename, “close logfile: thread%ld.log\n”, (unsigned long)pthread_self()); printf(logfilename);
fclose((FILE *)logfile);
}
void thread_function(void args) { char logfilename[128]; sprintf(logfilename, “thread%ld.log”, (unsigned long)pthread_self());
FILE* logfile = fopen(logfilename, "w");
if (logfile != NULL)
{
pthread_setspecific(thread_log_key, logfile);
write_to_thread_log("Thread starting...");
}
return NULL;
}
int main()
{
pthread_t threadIDs[5];
pthread_key_create(&thread_log_key, close_thread_log);
for(int i = 0; i < 5; ++i)
{
pthread_create(&threadIDs[i], NULL, thread_function, NULL);
}
for(int i = 0; i < 5; ++i)
{
pthread_join(threadIDs[i], NULL);
}
return 0;
1.4 使用场景(认知有限,待补充)
- 统计线程的一些性能数据:运行时间,运行次数等等。
- 实现线程的一些本地缓存机制:例如每个线程都维护自己的一块内存块。