[英]pthread_create error:
i have written this piece of code for my own purpose.it will create a thread which runs a routine named event_handler().the routine event_handler will take an instance of the class object QApplication as an argument and invoke its exec() method. 我已经出于个人目的编写了这段代码。它将创建一个线程,该线程运行名为event_handler()的例程。例程event_handler将类对象QApplication的实例作为参数并调用其exec()方法。
#include <pthread.h>
void event_handler(void * &obj)
{
QApplication* app = reinterpret_cast<QApplication*>(&obj);
app.exec();
}
int main(int argc, char **argv)
{
pthread_t p1;
QApplication a(argc, argv);
pthread_create(&p1, NULL, &event_handler,(void *) &a);
//do some computation which will be performed by main thread
pthread_join(*p1,NULL);
}
But whenever i am trying to build this piece of code, i am getting this error 但是每当我尝试构建这段代码时,我都会收到此错误
main.cpp:10: error: request for member ‘exec’ in ‘app’, which is of non-class type ‘QApplication*’
main.cpp:34: error: invalid conversion from ‘void (*)(void*&)’ to ‘void* (*)(void*)’
main.cpp:34: error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’
what is the problem in my code.(keeping in mind that i am a newbie in this area it may be a very silly mistake :-) ) 我的代码有什么问题。(请记住,我是该领域的新手,这可能是一个非常愚蠢的错误:-))
The thread function have to take a void
pointer as its argument, not a reference to an object. 线程函数必须将
void
指针作为其参数,而不是对对象的引用。 You can later typecast this to the correct pointer type: 您可以稍后将其转换为正确的指针类型:
void event_handler(void* pointer)
{
QApplication* app = reinterpret_cast<QApplication*>(pointer);
app->exec();
}
You also pass the thread identifier wrong to pthread_join
. 您还将错误的线程标识符传递给
pthread_join
。 You should not use the dereferencing operator there. 您不应该在此处使用解引用运算符。
I also recommend you look into the new C++11 threading functionality . 我还建议您研究新的C ++ 11 线程功能 。 With
std::thread
you can simply do: 使用
std::thread
您可以简单地执行以下操作:
int main()
{
QApplication app;
std::thread app_thread([&app]() { app.exec(); });
// Other code
app_thread.join();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.