pthread_create in member of class

独自空忆成欢 提交于 2019-12-11 19:15:00

问题


Suppose I have the following class:

*.h :

class MyClass{
    void caller();
    int threadProcuder(void *args);
};

*cpp :

void MyClass::caller()
{
    pthread_t i;
    pthread_create(&i,NULL,(void*(*)(void*))&MyClass::threadProcedure,(void*)this);
}

int MyClass::threadProcedure(void *args) 
{
    cout << "body of thread" << endl;
}

Unforunately, thread doesn't run.


回答1:


The correct way is:

// Must declare the callback is extern "C" 
// As you are calling back from a C library.
// As this is compiles as C it can only call functions that use the C ABI
// There is no guarantee in the C++ standard that static member functions
// use the same ABI as a "C" function.
//
// Certain C++ ABI definitions do make this explicit but using this knowledge
// Renders your code non portable. If you use a C++ static member it will likely
// break in the future and when it does tracking down the problem will be nearly
// imposable.
extern "C" void* threadProcuder(void *args);

class MyClass{
    void caller();
    void* threadProcuder();
};

void MyClass::caller()
{
    // NOTE: This function should NOT be called from the constructor.
    //       You should really wait until the object is fully constructed
    //       before letting a thread run around inside your object
    //       otherwise the thread may will start playing with members that
    //       are not fully constructed.
    pthread_t i;
    pthread_create(&i,NULL,&threadProcedure,this);
}

void* threadProcuder(void *args)
{
    // I use reinterpret_cast<> here to make it stand out.
    // Others prefer static_cast<>. Both are valid and guaranteed to work.
    // Casting a pointer to/from void* is guaranteed by the standard
    MyClass* obj    = reinterpret_cast<MyClass*>(args);
    void*    result = NULL;
    try
    {
        result = obj->threadProcuder();
    }
    catch(...) {}   // you MUST catch all exceptions
                    // Failing to do so is very undefined.
                    // In most pthread_application allowing exceptions to escape
                    // usually (but not always) leads to application termination.
    return result;
}



回答2:


EDIT: The function passed to pthread_create must be declared extern "C". See https://stackoverflow.com/a/2068048/786714 for a better explanation as to why this is the case.

You cannot use a static member-function as my original answer stated, though it may work as it its undefined behavior.




回答3:


I solved it, my format is correct, i didn't call in my constructor.



来源:https://stackoverflow.com/questions/11741051/pthread-create-in-member-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!