MST

星途 面试题库

面试题:C语言中Linux线程局部存储的基本范围界定

在Linux环境下使用C语言,线程局部存储(TLS)在单个线程内的作用范围是怎样的?请举例说明如何在代码中定义和使用线程局部存储变量,以体现其范围特性。
29.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

线程局部存储(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;
}

代码说明

  1. 定义线程局部存储变量:使用__thread关键字定义了一个线程局部存储变量thread_local_variable
  2. 线程函数thread_function函数设置并访问线程局部变量。每个线程都独立地设置和修改自己的thread_local_variable实例。
  3. 主线程:在main函数中创建了两个线程,并传递不同的参数给线程函数。两个线程对thread_local_variable的操作相互独立,体现了线程局部存储变量在单个线程内的作用范围特性。