Reputation: 571
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.
#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 :-) )
Upvotes: 0
Views: 998
Reputation: 409404
The thread function have to take a void
pointer as its argument, not a reference to an object. 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
. You should not use the dereferencing operator there.
I also recommend you look into the new C++11 threading functionality. With std::thread
you can simply do:
int main()
{
QApplication app;
std::thread app_thread([&app]() { app.exec(); });
// Other code
app_thread.join();
}
Upvotes: 4