假设我有以下课程:
* .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;
}
不幸的是,线程没有运行。
答案 0 :(得分: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;
}
答案 1 :(得分:1)
编辑:传递给pthread_create
的函数必须声明为extern "C"
。有关为何会出现这种情况的详细解释,请参阅https://stackoverflow.com/a/2068048/786714。
您不能使用静态成员函数作为我的原始答案,尽管它可能会因其未定义的行为而起作用。
答案 2 :(得分:0)
我解决了,我的格式是正确的,我没有在我的构造函数中调用。