MST

星途 面试题库

面试题:C语言中Linux线程局部存储初始化的基本方式

在Linux环境下使用C语言,简述线程局部存储(TLS)初始化的基本步骤和涉及的关键函数,并举例说明如何定义一个线程局部存储变量及其初始化。
31.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

线程局部存储(TLS)初始化基本步骤及关键函数

  1. 定义线程局部存储变量:使用 __thread 关键字声明变量,表明该变量是线程局部存储的。例如:__thread int myTLSVariable;
  2. 初始化函数:在Linux下,对于一些复杂的初始化,可能会用到 pthread_key_create 函数来创建一个线程特定数据的键,pthread_key_create 函数原型为:
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
  • 第一个参数 key 是指向 pthread_key_t 类型变量的指针,用于存储创建的键。
  • 第二个参数 destructor 是一个清理函数指针,当线程退出时会调用这个函数来清理与该键关联的线程特定数据。如果不需要清理,可设为 NULL
  1. 设置和获取线程局部存储数据
    • pthread_setspecific 函数用于将一个值与键关联起来,即设置线程局部存储的数据。函数原型为:
int pthread_setspecific(pthread_key_t key, const void *value);
  • pthread_getspecific 函数用于获取与键关联的值,即获取线程局部存储的数据。函数原型为:
void *pthread_getspecific(pthread_key_t key);

示例

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

// 使用 __thread 关键字定义线程局部存储变量
__thread int myTLSVariable = 42;

// 清理函数
void cleanup(void *arg) {
    printf("Cleaning up: %d\n", *((int *)arg));
}

// 线程函数
void *thread_function(void *arg) {
    // 使用 pthread_key_create 创建键
    pthread_key_t key;
    pthread_key_create(&key, cleanup);

    // 设置线程局部存储数据
    int *local_value = (int *)malloc(sizeof(int));
    *local_value = 100;
    pthread_setspecific(key, local_value);

    // 获取线程局部存储数据
    int *retrieved_value = (int *)pthread_getspecific(key);
    printf("Thread retrieved value: %d\n", *retrieved_value);

    // 释放内存
    free(retrieved_value);
    pthread_key_delete(key);
    return NULL;
}

int main() {
    pthread_t thread;
    // 创建线程
    pthread_create(&thread, NULL, thread_function, NULL);
    // 等待线程结束
    pthread_join(thread, NULL);

    printf("Main thread: myTLSVariable = %d\n", myTLSVariable);
    return 0;
}

在上述示例中,定义了 myTLSVariable 为线程局部存储变量并初始化为42。同时在 thread_function 中展示了使用 pthread_key_createpthread_setspecificpthread_getspecific 函数的用法。