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

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

    Where available, you could use pthread-functions pthread_getspecific and pthread_setspecific for a getter and a setter for that purpose:

    #include 
    
    class A {
    private:
    #define varKey 100L
    
    public:
    
        int getVar() {
            void *mem = pthread_getspecific(varKey);
            if(mem)
                return *((int*)mem);
            else
                return 0;
        }
    
        void setVar(int val) {
            void *mem = malloc(sizeof(int));
            *((int*)mem)=val;
            pthread_setspecific(varKey, mem);
        }
    
        ~A() {
            void *mem = pthread_getspecific(varKey);
            if (mem)
                free(mem);
        }
    
    };
    

提交回复
热议问题