How to allocate thread local storage?

前端 未结 9 1221
夕颜
夕颜 2020-12-07 10:40

I have a variable in my function that is static, but I would like it to be static on a per thread basis.

How can I allocate the memory for my C++ class such that eac

相关标签:
9条回答
  • 2020-12-07 11:26

    Folly (Facebook Open-source Library) has a portable implementation of Thread Local Storage.

    According its authors:

    Improved thread local storage for non-trivial types (similar speed as pthread_getspecific but only consumes a single pthread_key_t, and 4x faster than boost::thread_specific_ptr).

    If your looking for a portable implementation of Local Storage Thread, this library is a good option.

    0 讨论(0)
  • 2020-12-07 11:27

    C++11 specifies a thread_local storage type, just use it.

    AnotherClass::threadSpecificAction()
    {
      thread_local MyClass *instance = new MyClass();
      instance->doSomething();
    }
    

    One optional optimization is to also allocate on thread local storage.

    0 讨论(0)
  • 2020-12-07 11:36
    #include <boost/thread/tss.hpp>
    static boost::thread_specific_ptr< MyClass> instance;
    if( ! instance.get() ) {
        // first time called by this thread
        // construct test element to be used in all subsequent calls from this thread
        instance.reset( new MyClass);
    }
        instance->doSomething();
    
    0 讨论(0)
提交回复
热议问题