1.线程局部存储

1.1 概述

线程局部存储能够将一个变量分为多份,每个线程可以使用属于自己的一份,也就是说:A线程对该数据处理的结果并不会影响B线程中的该数据。

1.2 API介绍

  1. #include <pthread.h>
  2. /**
  3. * key:线程局部存储变量key值:
  4. * void (*destructor)(void*):函数指针,用来释放线程局部存储变量
  5. */
  6. int pthread_key_create(pthread_key_t* key, void (*destructor)(void*));
  7. int pthread_key_delete(pthread_key_t key);
  8. int pthread_setspecific(pthread_key_t key, const void* value);
  9. void* pthread_getspecific(pthread_key_t key);
  10. __thread int val = 0;
  1. pthread_key_create: 创建线程局部存储key对象,同时指定线程局部存储变量释放函数。
  2. pthread_key_create:用来删除线程局部存储key对象。
  3. pthread_setspecific:先key对象指向的区域设置线程局部存储变量。
  4. pthread_getspecific:从key对象指向的区域获取线程局部存储变量。
  5. __thread:可以直接定义一个线程局部存储变量,非常简单。

    1.3 实例

    ```cpp

    include

    include

    include

//线程局部存储key pthread_key_t thread_log_key;

void write_to_thread_log(const char* message) { if (message == NULL) return;

  1. FILE* logfile = (FILE*)pthread_getspecific(thread_log_key);
  2. fprintf(logfile, "%s\n", message);
  3. fflush(logfile);

}

void close_thread_log(void* logfile) { char logfilename[128]; sprintf(logfilename, “close logfile: thread%ld.log\n”, (unsigned long)pthread_self()); printf(logfilename);

  1. fclose((FILE *)logfile);

}

void thread_function(void args) { char logfilename[128]; sprintf(logfilename, “thread%ld.log”, (unsigned long)pthread_self());

  1. FILE* logfile = fopen(logfilename, "w");
  2. if (logfile != NULL)
  3. {
  4. pthread_setspecific(thread_log_key, logfile);
  5. write_to_thread_log("Thread starting...");
  6. }
  7. return NULL;

}

int main() { pthread_t threadIDs[5];
pthread_key_create(&thread_log_key, close_thread_log); for(int i = 0; i < 5; ++i) { pthread_create(&threadIDs[i], NULL, thread_function, NULL); }

  1. for(int i = 0; i < 5; ++i)
  2. {
  3. pthread_join(threadIDs[i], NULL);
  4. }
  5. return 0;

} ```

1.4 使用场景(认知有限,待补充)

  1. 统计线程的一些性能数据:运行时间,运行次数等等。
  2. 实现线程的一些本地缓存机制:例如每个线程都维护自己的一块内存块。