I am writing a multi-threaded Qt Application but because of OpenGL related calls some part of code has to be always executed in main thread.
Rough code to simulate the problem will be:
QMutex mutex;
void foo1()
{
mutex.lock();
//do something
mutex.unlock();
}
class CBHandler : public QObject
{
public:
CBHandler(QObject *parent = NULL)
{
connect(this, SIGNAL(requestCallbackExec()), SLOT(runCallback()), Qt::BlockingQueuedConnection);
}
static CBHandler *Instance();
public slots:
void runCallback ()
{
//in main thread as object lies there
//do something
}
signals:
void requestCallbackExec ();
};
class Thread1
{
void run()
{
while(1)
{
mutex.lock();
CBHandler::Instance()->emit requestCallbackExec();
mutex.unlock();
}
}
};
void main()
{
Thread1 thread;
CBHandler cbhandler;
thread.start();
while(1)
{
if(/*some key pressed*/)
{
foo1();
}
}
}
Above code ensures that "do something" is always executed in main thread. But problem is, if mutex is locked by Thread1 and main thread tries to call foo1 then main thread sleeps when trying to lock mutex. And since main thread is sleeping, mutex locked by Thread1 never gets unlocked because of 'requestCallbackExec' signal never getting processed.
Aucun commentaire:
Enregistrer un commentaire