使用TLS很简单,只需要用__thread关键字来修饰一个"全局变量",比如下面例子里的tid. 它在不同的thread里被输出的时候就是输出不同的值
#include <stdio.h> #include <pthread.h< #define NUM_THREADS 5 __thread long tid; void print_tid() { printf("Hello World! It's me, thread #%ld!\n", tid); } void *run_thread(void *threadid) { tid = (long)threadid; print_tid(); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for(t=0; t<NUM_THREADS; t++){ rc = pthread_create(&threads[t], NULL, run_thread, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } /* Last thing that main() should do */ pthread_exit(NULL); }运行
$ gcc test_tls.c $ ./a.out Hello World! It's me, thread #0! Hello World! It's me, thread #1! Hello World! It's me, thread #2! Hello World! It's me, thread #3! Hello World! It's me, thread #4!