TLS(Thread-local storage)
Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> __thread int tls1; int tls2; void *threadfun() { tls1=10; tls2=10; sleep(5); printf("tls1 in thread: %d\n",tls1); printf("tls2 in thread: %d\n",tls2); return 0; } int main() { pthread_t pt1; int err; err=pthread_create(&pt1,NULL,threadfun,NULL); if(err!=0) { printf("create thread failed\n"); } else { tls1=20; tls2=20; sleep(10); printf("tls1 in main thread: %d\n",tls1); printf("tls2 in main thread: %d\n",tls2); } } |
运行结果
1 2 3 4 5 6 7 |
# ./tls tls1 in thread: 10 tls2 in thread: 10 tls1 in main thread: 20 tls2 in main thread: 10 |
关于TLS的详细介绍,cppblog里有一篇比较易于理解的文章,偶只是小试一下: