Using a c++ class member function as a c callback function, thread safe version

前端 未结 2 556
粉色の甜心
粉色の甜心 2021-01-22 10:04

The original question, got a great answer as to how to do the non thread safe version.

Here is the code, which I\'ve tried to slightly modify to get to work:

<         


        
2条回答
  •  攒了一身酷
    2021-01-22 10:37

    If each thread just need one instance of specific object, you can use a global variable for object pointer with __thread storage class, __thread makes global variables unique to that thread.

    Using monotonic class with static member for callback is another solution, like previous solution, you can use __thread for separating monothonic class instances for each thread.

    Also be aware, __thread isn't standard thing

    Edit

    Here is an example

    class.h

    class someClass{
         private:
             someMethod(){ ... }
    }
    

    class.cpp

    __thread void * objectPointer;
    
    void initialize(){
        someClass * classPtr = new someClass();
        objectPointer = (void *) classPtr;
    }
    
    void * callbackFunction(void * args){
        someClass * obj = objectPointer;
        obj->someMethod();
    }
    

提交回复
热议问题