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

后端 未结 3 1741
天命终不由人
天命终不由人 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:25

    You can't have a non-static member declared thread_local. See cppreference. In particular:

    the thread_local keyword is only allowed for objects declared at namespace scope, objects declared at block scope, and static data members.

    If you don't want to use pthreads (tricky on Windows), some container is your only option.

    One choice is a variant of std::unordered_map. (You could write a class to wrap it and protect the map with a mutex.)

    Another initially attractive option is a thread_local static member of A which maps A* to B will avoid any need for locks.

    class A {
        static thread_local std::unordered_map s_B;
        ....
    };
    

    usage:

    void A::foo() {
        B& b = s_B[this];  // B needs to be default constructable.
        ...
    

    The catch is that you need some way to remove elements from the s_B map. That's not too much of a problem if A objects are actually locked to a particular thread, or if you have some way to invoke functions on another thread - but it's not entirely trivial either. (You may find it safer to use a unique identifier for A which is an incrementing 64-bit counter - that way there is much less risk of the identifier being reused between destroying the A object and the message to remove the B from all the maps being processed.)

提交回复
热议问题