__thread
是 Linux 下的一种线程局部存储(Thread Local Storage,TLS)的实现方式。它允许每个线程拥有其独立的数据副本,这些数据对于每个线程来说都是私有的,不会被其他线程访问或修改。
线程局部存储(TLS):是一种机制,用于在多线程程序中为每个线程分配独立的存储空间。这样,每个线程都可以独立地访问和修改自己的数据副本,而不会影响其他线程的数据。
__thread 关键字:在 C/C++ 中,__thread
是一个编译器扩展,用于声明线程局部变量。这些变量在每个线程中都有独立的实例。
#include <pthread.h>
#include <stdio.h>
__thread int thread_local_var = 0; // 线程局部变量
void* thread_func(void* arg) {
thread_local_var = *(int*)arg;
printf("Thread %ld: thread_local_var = %d\n", pthread_self(), thread_local_var);
return NULL;
}
int main() {
pthread_t threads[5];
int thread_args[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
问题:某些编译器可能不支持 __thread
关键字。
解决方法:
__declspec(thread)
(Windows 平台)或 __attribute__((thread))
(GCC 和 Clang)作为替代。pthread_key_create
和 pthread_setspecific
。示例代码(使用 GCC 的 __attribute__((thread))
):
#include <pthread.h>
#include <stdio.h>
__attribute__((thread)) int thread_local_var = 0;
void* thread_func(void* arg) {
thread_local_var = *(int*)arg;
printf("Thread %ld: thread_local_var = %d\n", pthread_self(), thread_local_var);
return NULL;
}
int main() {
pthread_t threads[5];
int thread_args[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
通过这种方式,可以确保在不同编译器和平台上都能实现线程局部存储的功能。
领取专属 10元无门槛券
手把手带您无忧上云