windows线程本地存储__declspec (thread) 语法问题?

qq_33892956 2016-02-26 09:28:35
Microsoft对C的扩充功能使这件工作更加容易。
只要在要对每个线程都保留不同内容的变量前加上__declspec
(thread)就好了。对于全局静态变量,则为:

__declspec (thread) int iGlobal = 1 ;

对于函数内部的静态变量,则为:

__declspec (thread) static int iLocal = 2 ;

我很疑惑既然是线程本地存储,就说明这个变量是线程私有的,也就是只有定义这个变量的线程才能用,那为什么__declspec (thread) 还可以让变量成为全局静态变量?难不成这个变量还能给别的线程用?这样的话不就不是TLS了么?还是说这个全局变量虽然是全局的,但只能给本线程使用?但是无论是我说的哪种情况,我认为只要加上static的这个版本也就是__declspec (thread) static这一种形式就够了。
上面说了这么多,意思其实就一个,千万别被我绕晕
...全文
278 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dustpg 2016-02-27
  • 打赏
  • 举报
回复
static是每个源文件单独一个实例,msc自带的扩展没用过,毕竟最新的C/C++标准都支持线程本地储存了. lz应该附上简单的测试代码.
qq_33892956 2016-02-27
  • 打赏
  • 举报
回复
引用 3 楼 schlafenhamster 的回复:
对于函数内部的静态变量 , 是 static 把 它变成 静态变量 ,与 __declspec( thread ) 没关系。
那么单纯的__declspec( thread )就不是静态变量了?如果不是静态变量的话,不就不是TLS了吗?
schlafenhamster 2016-02-27
  • 打赏
  • 举报
回复
Example The following code declares an integer thread local variable and initializes it with a value: // Example of the thread attribute __declspec( thread ) int tls_i = 1;
schlafenhamster 2016-02-27
  • 打赏
  • 举报
回复
对于函数内部的静态变量 , 是 static 把 它变成 静态变量 ,与 __declspec( thread ) 没关系。

15,979

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 界面
社区管理员
  • 界面
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧