面试题答案
一键面试线程局部存储(TLS)在单个线程内的作用范围
线程局部存储(TLS)变量在单个线程内的作用范围是该线程的整个生命周期。每个线程都有自己独立的TLS变量实例,不同线程的TLS变量相互隔离,修改一个线程的TLS变量不会影响其他线程的同名变量。
代码示例
以下是在Linux环境下使用C语言定义和使用线程局部存储变量的示例:
#include <pthread.h>
#include <stdio.h>
// 定义线程局部存储变量
__thread int thread_local_variable;
void* thread_function(void* arg) {
// 设置线程局部变量的值
thread_local_variable = *((int*)arg);
printf("Thread %ld: thread_local_variable = %d\n", (long)pthread_self(), thread_local_variable);
// 在线程内可以随时访问和修改该变量
thread_local_variable += 10;
printf("Thread %ld: After modification, thread_local_variable = %d\n", (long)pthread_self(), thread_local_variable);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int value1 = 10;
int value2 = 20;
// 创建两个线程
pthread_create(&thread1, NULL, thread_function, &value1);
pthread_create(&thread2, NULL, thread_function, &value2);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
代码说明
- 定义线程局部存储变量:使用
__thread
关键字定义了一个线程局部存储变量thread_local_variable
。 - 线程函数:
thread_function
函数设置并访问线程局部变量。每个线程都独立地设置和修改自己的thread_local_variable
实例。 - 主线程:在
main
函数中创建了两个线程,并传递不同的参数给线程函数。两个线程对thread_local_variable
的操作相互独立,体现了线程局部存储变量在单个线程内的作用范围特性。