bob*_*bob 2 c++ multithreading
我正在尝试使用以下代码在c ++中创建一个线程:
pthread_t mythread;
void* f (void*) = MyClass::myfunction;
pthread_create(&mythread, NULL, &f, NULL);
Run Code Online (Sandbox Code Playgroud)
它不起作用.知道什么是错的吗?
myfunction的类型:
void* MyClass::myfunction(void* argv);
Run Code Online (Sandbox Code Playgroud)
返回的错误是:
error: declaration of ‘void* Class::f(void*)’ has ‘extern’ and is initialized
error: invalid pure specifier (only ‘= 0’ is allowed) before ‘::’ token
error: function ‘void* Class::f(void*)’ is initialized like a variable
Run Code Online (Sandbox Code Playgroud)
您将声明f为函数而不是函数指针.它应该是:
void* (*f) (void*) = &MyClass::myfunction;
^^^^
pthread_create(&mythread, NULL, f, NULL);
^ no & since it's already a pointer
Run Code Online (Sandbox Code Playgroud)
这也只有在myfunction静态时才有效,因为你不能将指向成员函数的指针转换为指向函数的指针.
如果你确实需要线程来对特定对象执行非静态成员函数,那么一种方法是编写一个静态包装器,将对象作为参数:
class MyClass {
public:
void start_thread() {
// Pass "this" to the thread we're creating
pthread_create(&mythread, NULL, &MyClass::thread_entry, this);
}
private:
static void * thread_entry(void * object) {
// Call the member function on the object passed to the thread
return static_cast<MyClass*>(object)->thread();
}
void * thread() {
// do the interesting stuff, with access to the member variables
}
};
Run Code Online (Sandbox Code Playgroud)
当然,这些天有一个标准的线程库,不需要这种舞蹈:
std::thread thread(&MyClass::thread, this);
Run Code Online (Sandbox Code Playgroud)