I seem to have a major understanding problem with threads, mutexes and waitconditions. Assume I have the following thread class:
{
public:
MyThread
() : QThread(), exec
( true ) {
start();
}
void run()
{
mutex.lock();
while( exec )
{
// do stuff here
// ...
// wait for wake up
condition.wait( &mutex );
}
mutex.unlock();
}
void stop()
{
exec = false;
condition.wakeAll();
wait();
}
private:
bool exec;
};
class MyThread : public QThread
{
public:
MyThread() : QThread(), exec( true )
{
start();
}
void run()
{
mutex.lock();
while( exec )
{
// do stuff here
// ...
// wait for wake up
condition.wait( &mutex );
}
mutex.unlock();
}
void stop()
{
QMutexLocker m( &mutex );
exec = false;
condition.wakeAll();
wait();
}
private:
bool exec;
QMutex mutex;
QWaitCondition condition;
};
To copy to clipboard, switch view to plain text mode
Within the thread, I lock its QMutex outside the loop right away. Within the loop, stuff gets done, then the thread gets put to sleep by the wait condition and the QMutex gets unlocked, as far as I understand how QWaitCondition works.
When the thread is supposed to be stopped by the main thread via the stop() function, a lock on the QMutex is requested again, to ensure the main thread waits until the thread enters the wait condition again, then the loop variable is changed to false to make the thread exit after the next loop, the main thread wakes up the QThread and waits for it to exit.
Somewhere in this chain of logic I am missing something, because this way, a deadlock is created. When the main thread calls stop(), it waits forever for the thread to finish while the thread waits forever to be woken up.
// edit: ugh, nvm, ... one day of frustration and now at lunch while being away from the code I notice the simplest thing of course: I should unlock the mutex before waiting for the thread to finish :P
void stop()
{
mutex.lock();
exec = false;
condition.wakeAll();
mutex.unlock();
wait();
}
void stop()
{
mutex.lock();
exec = false;
condition.wakeAll();
mutex.unlock();
wait();
}
To copy to clipboard, switch view to plain text mode
Bookmarks