I have a GUI thread where I call write(QString text)
method of another MyQThread
.
MyQthread
contains QMutex mutex
and QList<QString> list
. Here is the write()
and run()
methods of MyQThread
:
void MyQThread::write(QString text)
{
mutex.lock();
list.append(text); //Point C
mutex.unlock();
start(); //Point D
}
void MyQThread::run()
{
mutex.lock();
while(!list.isEmpty())
{
QString text = list.takeFirst();
mutex.unlock();
...//do something
mutex.lock(); //Point A
}
mutex.unlock(); //Point B
}
For example we are at the 'point A'. After this point we are checking the list and it is empty, so we are going to 'point B'. At this moment write()
is called, mutex is still locked, so GUI thread is waiting before 'point C'.
Now we are at the 'point B', after this GUI thread is unlocked and start() ('Point D') is called.
Is it possible, that at 'point D' MyQThread is still running?
In this case calling of start()
do nothing. And newly added item in the list
will not be processed in run()
until next call of the write()
.
Additional information. In my case here is only one instance of MyQThread.
@alexisdm thanks for the idea. What about this solution:
And what about the second parameter of
wait()
-unsigned long time = ULONG_MAX
.It seems that in my case it will not be error, when
write()
method is not called for a long time andwait()
will returnfalse
inrun()
afterULONG_MAX
. And in this case I need just to wait again...And in documentation is written:
Does it mean, that mutex will be always locked after
wait()
even if mutex was not locked beforewait()
orwait()
returns false?