你可以使用一个类或结构内螺纹的局部变量 [英] Can you use thread local variables inside a class or structure

查看:143
本文介绍了你可以使用一个类或结构内螺纹的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

筛选。

 结构some_struct
{
 //其他字段
 .....
 __thread INT TL;
}

我想这样做,但编译器给我这个错误。

  ./ cv.h:16:2:错误:'__thread'只允许在变量声明
        __thread INT TL;


解决方案

线程局部存储仅适用于静态变量。有是使非静态结构或类成员线程本地没有意义的。

本地(自动)变量总是特定于执行code,但由于它们驻留在数据或BSS段全局和静态变量的线程共享的线程。 TLS提供了一种机制,使这些全球性的局部变量的线程,这就是 __线程关键字达到什么 - 它指示编译器在每个线程同时创建变量的单独副本词法它仍然是一个全球性(例如,它可以被称为执行的同一个线程中的不同功能访问)。

非静态类成员和结构体放置在对象(类或结构)被分配在同一个地方 - 无论是在栈如果一个自动变量声明或堆上的malloc()被使用。无论哪种方式,每个线程接收的变量都有一个独特的存储位置和 __线程是不适用在这种情况下,因此你得到的编译错误。

Like this.

struct some_struct
{
 // Other fields
 .....
 __thread int tl;
}

I'm trying to do that but the compiler is giving me this error.

./cv.h:16:2: error: '__thread' is only allowed on variable declarations
        __thread int tl;

解决方案

Thread-local storage applies to static variables only. There is no point in making non-static structure or class members thread-local.

Local (automatic) variables are always specific to the thread that executes the code, but global and static variables are shared among threads since they reside in the data or BSS segment. TLS provides a mechanism to make those global variables local to the thread and that's what the __thread keyword achieves - it instructs the compiler to create a separate copy of the variable in each thread while lexically it remains a global one (e.g. it can be accessed by different functions called within the same thread of execution).

Non-static class members and structure members are placed in the same place where the object (class or structure) is allocated - either on the stack if an automatic variable is declared or in the heap if new or malloc() is used. Either way each thread receives a unique storage location for the variable and __thread is just not applicable in this case hence the compiler error you get.

这篇关于你可以使用一个类或结构内螺纹的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆