C++11 thread_local in gcc - alternatives

2020-02-12 07:19发布

问题:

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 want to use boost library.

回答1:

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



回答2:

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.



回答3:

GCC 4.8.0 includes support for the thread_local storage class.



回答4:

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;
}