线程本地存储(TLS)是一种机制,通过这样的机制进行变量分配。在每一个现存线程都有一个实例变量。这样的执行模型GCC用来实现这个,起源于IA-64处理器,可是已经被迁移到其它的处理器。它须要大量的支持连接器(ld)、动态连接器(ld.so)和系统库(libc.so和libpthread.so),所以不是到处都可用的。

在用户层,一个新的存储类扩展keyword:__thread.比如:

__thread int i;
extern __thread struct state s;
static __thread char *p;

这个keyword__thread能够单独使用。也能够和extern或者static配合使用,不能与其它的存储类说明符使用。当使用extern或者static。__thread必须在这些存储keyword后面使用。

看以下的样例:

/*File : thread.c
*Auth : sjin
*Date : 20141023
*Mail : 413977243@qq.com
*/ #include <stdio.h>
#include <pthread.h> #define MAX_THREADS 2 static __thread int i = 1; void *thr_func(void *arg)
{
printf("pself = %d,i = %d\n",pthread_self(),i);
i = ( int)pthread_self();
printf("pself = %d,i = %d\n",pthread_self(),i);
} int main()
{
int j = 0;
pthread_t thread_id[MAX_THREADS]; for(j = 0; j < MAX_THREADS;j++){
pthread_create(&thread_id[j],0,thr_func,NULL);
} for(j = 0; j < MAX_THREADS;j++){
pthread_join(thread_id[j],NULL);
} return 0;
}

执行结果:

pself = -1218581696,i = 1
pself = -1218581696,i = -1218581696
pself = -1226974400,i = 1
pself = -1226974400,i = -1226974400

參考资料:
 1、https://bugs.gentoo.org/show_bug.cgi?id=18316
2、https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html

最新文章

  1. VS2015/2013/2012 IIS Express Debug Classic ASP
  2. pods的安装和使用
  3. redis学习笔记——(3)
  4. POJ 3648 Wedding (2-SAT,经典)
  5. jQuery Validate验证框架使用
  6. HDU4003 Find Metal Mineral
  7. bzoj 1093 [ZJOI2007]最大半连通子图(scc+DP)
  8. Android Studio设置自己主动编project
  9. WP8.1程序开发中,如何加载本地文件资源或安装在程序包中的资源。
  10. 关于post利用之Python
  11. Kubernetes 笔记 08 Deployment 副本管理 重新招一个员工来填坑
  12. web plugins
  13. IntelliJ IDEA 创建Spring项目
  14. Linux内核分析——ELF文件格式分析
  15. ARouter原理剖析及手动实现
  16. 数据分析与挖掘 - R语言:贝叶斯分类算法(案例二)
  17. UVALive 7501 Business Cycle(二分)题解
  18. 转Python SciPy库——拟合与插值
  19. Chrome-Adobe Flash 无法正常使用
  20. LeetCode——Best Time to Buy and Sell Stock III

热门文章

  1. 二分搜索之C++实现
  2. SPOJ6717 Two Paths 树形dp
  3. 4144: [AMPPZ2014]Petrol (多源最短路+最小生成树+启发式合并)
  4. 某gov的逻辑漏洞
  5. hdu 4452 Running Rabbits 模拟
  6. .NET面试宝典-高级2
  7. 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM 对象强制转换为接口类型“Microsoft.Office.Interop.Excel._Application”
  8. 前些日子用css画的大白
  9. ThinkPHP中RBAC权限管理的简单应用
  10. 用最简单的例子理解适配器模式(Adapter Pattern)