How can I have non-static thread-local variable for each instance

后端 未结 3 1742
天命终不由人
天命终不由人 2021-01-18 10:47

The problem itself:

class B{/*...*/};
class A {
    /* members */
    NON-static thread_local B var; // and a thread_local variable here
            


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 11:05

    If you're willing to use tbb (which is free even though by Intel), you could use their tbb::enumerable_thread_specific template class (which essentially is something like std::unordered_map but lock free, I understand). Since the A are shared between threads, one such container per instance of A is required, but it appears B is better declared as a nested type. For example

    class A
    {
      struct B
      {
        B(const A*);
        void call(/* args */);
      };
      tbb::enumerable_thread_specific _B ([&]()->B { return {this}; } );
      void method(/* args */)
      {
        _B.local().call(/* args */);   // lazily creates thread local B if required.
      }
      /* ... */
    };
    

提交回复
热议问题