面试题答案
一键面试1. Linux C语言线程局部存储(TLS)基本原理
线程局部存储(TLS)是一种机制,它允许每个线程拥有自己独立的变量实例。当多个线程访问相同的变量名时,实际上访问的是各自线程私有的数据副本,而不是共享的全局变量。这使得每个线程可以独立地修改和使用这些变量,而不会影响其他线程。
在Linux下,TLS通常通过特定的编译器和运行时库支持来实现。线程启动时,运行时库会为每个线程分配一块私有存储区域,用于存放TLS变量。当线程访问TLS变量时,系统会根据线程上下文找到对应的私有副本进行操作。
2. C语言代码示例
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// 定义线程局部存储变量
__thread int counter = 0;
// 线程函数
void* thread_function(void* arg) {
// 每个线程对计数器进行自增操作
counter++;
printf("Thread %lu: counter value is %d\n", pthread_self(), counter);
return NULL;
}
int main() {
pthread_t threads[5];
int i;
// 创建5个线程
for (i = 0; i < 5; i++) {
if (pthread_create(&threads[i], NULL, thread_function, NULL) != 0) {
perror("Failed to create thread");
return 1;
}
}
// 等待所有线程结束
for (i = 0; i < 5; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("Failed to join thread");
return 2;
}
}
return 0;
}
在上述代码中:
- 使用
__thread
关键字定义了一个线程局部存储变量counter
。 - 每个线程在
thread_function
函数中对counter
进行自增操作,并输出自己线程的counter
值。 main
函数创建了5个线程,并等待它们全部执行完毕。每个线程的counter
变量是独立的,互不影响。