0

假设我有以下课程:

* .h

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

* cp

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;
}

不幸的是,线程没有运行。

4

3 回答 3

5

正确的方法是:

// 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;
}
于 2012-07-31T14:43:29.120 回答
1

编辑:传递给的函数pthread_create必须声明extern "C"。有关为什么会这样的更好解释,请参阅https://stackoverflow.com/a/2068048/786714 。

您不能像我原来的回答所说的那样使用静态成员函数,尽管它可能会因其未定义的行为而起作用。

于 2012-07-31T13:34:37.047 回答
0

我解决了,我的格式是正确的,我没有调用我的构造函数。

于 2012-07-31T13:27:56.690 回答