C++11 thread_local in gcc - alternatives

后端 未结 4 777
孤街浪徒
孤街浪徒 2020-12-19 09:34

As I can see at: http://gcc.gnu.org/projects/cxx0x.html thread_local keyword is unfortunately unsupported in gcc yet.

Are there any alternatives for that? I don\'t w

相关标签:
4条回答
  • 2020-12-19 09:47

    The gcc compiler has a storage class __thread that might be close enough.

    http://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html

    0 讨论(0)
  • 2020-12-19 09:50

    GCC 4.8.0 includes support for the thread_local storage class.

    0 讨论(0)
  • 2020-12-19 09:51

    According to this GCC documentation page, you should try to use __thread as a qualifier (like volatile or const are) for your thread local storage.

    0 讨论(0)
  • 2020-12-19 09:54

    Here's an example usage of the __thread compiler extension (didn't see one above). It is used to create a singleton for each thread called ServiceLocator.

    So this is the (abbreviated) header. Here I have the thread local variable as a member of the class.

    class ServiceLocator :  public ImmutableServiceLocator {
    private:
        static __thread ServiceLocator* locator;
    public:
        void ServiceLocator::setAsServiceLocator();
        ImmutableServiceLocator& ServiceLocator::getServiceLocator();
    };
    

    Then you have to put a declaration of the thread local variable in your implementation or else your linker gets confused (I don't know why, sorry), and you can treat the thread local variable just like a static one:

    __thread ServiceLocator* ServiceLocator::locator;
    
    
    void ServiceLocator::setAsServiceLocator() {
        locator = this;
    }
    
    ImmutableServiceLocator& ServiceLocator::getServiceLocator() {
        return *locator;
    }
    
    0 讨论(0)
提交回复
热议问题