• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
我的人生我来写
博客园    首页    新随笔    联系   管理    订阅  订阅

gcc 中__thread 关键字的示例代码

__thread 关键字的解释:
 
Thread Local Storage 
线程局部存储(tls)是一种机制,通过这一机制分配的变量,每个当前线程有一个该变量的实例.
gcc用于实现tls的运行时模型最初来自于IA-64处理器的ABI,但以后被用到其它处理器上。
它需要链接器(ld),动态连接器(ld.so)和系统库(libc.so,libpthread.so)的全力支持.因此它不是到处可用的。
注意:__thread 前面是两个_别闹错哦;
 
示例代码:
  1 #include<iostream>
  2 #include<pthread.h>
  3 #include <unistd.h>
  4 #define D "-----------------------------------------"
  5 using namespace std;
  6 
  7 
  8 static __thread int a=12;
  9 
 10 
 11 void *thread1(void *arg);
 12 void *thread2(void *arg);
 13 
 14 int main()
 15 {
 16         pthread_t pid,pid1;
 17 
 18         pthread_create(&pid,NULL,thread1,NULL);
 19         pthread_create(&pid1,NULL,thread2,NULL);
 20 
 21 
 22         pthread_join(pid,NULL);
 23         pthread_join(pid,NULL);
 24 
 25         cout<<"main_a="<<a<<"\t"<<"addr_a="<<&a<<endl;
 26 
 27 
 28 }
 29 
 30 void *thread1(void *arg)
 31 {
 32         cout<<"I am thread1"<<endl;
 33         cout<<"a="<<a<<"\t"<<&a<<endl;
 34         sleep(1);
 35         a=1;
 36         cout<<"thread1->a="<<a<<"\t"<<"add_a="<<&a<<endl;
 37         cout<<D<<endl;
 38         return NULL;
 39 }
 40 void *thread2(void *arg)
 41 {
 42 
 43         cout<<"I am thread2"<<endl;
 44 
 45         cout<<"a="<<a<<"\t"<<&a<<endl;
 46         a=2;
 47         cout<<"thread2->a="<<a<<"\t"<<"add_a="<<&a<<endl;
 48         cout<<D<<endl;
 49         return NULL;
 50 }

执行结果:

zn@zn:~$ ./a.out 
I am thread2
a=12    0x7f7912b4a6fc
thread2->a=2    add_a=0x7f7912b4a6fc
-----------------------------------------
I am thread1
a=12    0x7f791334b6fc
thread1->a=1    add_a=0x7f791334b6fc
-----------------------------------------
main_a=12    addr_a=0x7f79144b473c
 

分析:

  该程序为了测试这个关键字的作用;

  介绍一下程序,

        首先在一开始定义一个全局变量a=12,其次声明连个线程的回调函数这两个函数作用,

        用于先打印一下a的值然后再改变在打印a的值,至于为什么这样做,是想验证一下他是不是写时拷贝,

        然后主程序就是开辟两个线程并等待其完成最后再打印一下a的值及地址来确定主线程是否有影响;

  最终分析:

      通过结果我们可以看到这个关键字作用是,只要其他线程用它他会直接在自己的线程栈上创建该对象并保留其原有的值;

        不会干扰其他线程中的该值;

posted @ 2019-01-07 14:06  我的人生我来写  阅读(1246)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3