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.
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;
}
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.
我解决了,我的格式正确,没有在构造函数中调用。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.