[英]pthread_create in member of class
Suppose I have the following class: 假设我有以下课程:
* .h : * .h :
class MyClass{
void caller();
int threadProcuder(void *args);
};
* cpp : * 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"
. 编辑:传递给pthread_create
的函数必须声明为extern "C"
。 See https://stackoverflow.com/a/2068048/786714 for a better explanation as to why this is the case. 请参阅https://stackoverflow.com/a/2068048/786714 ,以更好地解释为什么会这样。
You cannot use a static member-function as my original answer stated, though it may work as it its undefined behavior. 您不能使用静态成员函数作为我的原始答案,尽管它可能会发挥作用,因为它具有未定义的行为。
我解决了,我的格式正确,没有在构造函数中调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.