6

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Dejwi
  • 4,393
  • 12
  • 45
  • 74

4 Answers4

7

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

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • I tried. Unsuccessfully. Simple: __thread int a; Produces an error: error: storage class specified for 'a' – Dejwi Feb 04 '12 at 17:16
  • http://pastebin.com/y1Fsqnat Everything is fine if I add static keyword. But then, all objects of class, which belongs to the same thread, will share this variable between them. – Dejwi Feb 04 '12 at 17:56
  • 4
    But this is the definition of thread local storage! It cannot be specific to an object (use fields for that)! And an object don't belong to a particular thread, unless you allocate it on stack by making it a local variable! – Basile Starynkevitch Feb 04 '12 at 18:43
  • 1
    @Basile But even then you _could_ pass a reference or pointer to the object to another thread. (Doesn't make it a good idea normally, but I'd be willing to bet that someone has a sane use for it.) – Donal Fellows Aug 23 '12 at 06:30
4

GCC 4.8.0 includes support for the thread_local storage class.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
4

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

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;
}
Todd
  • 317
  • 1
  • 11