PDA

View Full Version : Qthread mutex



dognzhe
14th May 2009, 03:11
private bool stopped;
......

void Thread::run()
{
forever {
mutex.lock();
if (stopped) {
stopped = false;
mutex.unlock();
break;
}
mutex.unlock();
cerr << qPrintable(messageStr);
}
cerr << endl;
}

I don't understand why do we have to use mutex to lock the memeber of this class?
when you create the object of this class and call start() to start the thread, this object is unique, there is only one "stopped" !! why do we have to lock it before to write to it?

wagmare
14th May 2009, 06:34
but how many threads try to change the value stopped concurrently .. we should provide a queue to access the stopped value using QMutex , QSemaphores ...

dognzhe
15th May 2009, 03:58
but how many threads try to change the value stopped concurrently .. we should provide a queue to access the stopped value using QMutex , QSemaphores ...

this is only one thread to access stopped!!!!! this is memeber variables, one instance of this class will only one stopped!!! there is only one thread could access this variable, why mutex it????

wagmare
15th May 2009, 07:42
this is only one thread to access stopped!!!!! this is memeber variables, one instance of this class will only one stopped!!! there is only one thread could access this variable, why mutex it????

then no need for mutex .. if there is only one call for the thread run at a time ... if more than one thread function is called at a time and try to access thread class variables then we can go for Synchronization classes: QMutex, QReadWriteLock, QSemaphore, and QWaitCondition.

The QMutex class provides a means of protecting a variable or a piece of code so that only one thread can access it at a time

see the example ... it will clear all your doubts ...
QTDIR/example/network/threadedfortuneserver/

dognzhe
18th May 2009, 03:20
i don't really understand the thread in class.

if i have code like this


ServerThread *thread = new ServerThread( descriptor, this );

so i create the instance of this thread class. in the class I have


priave int ServerThread::num

run{
num ++;
}

thread->start();

now i create another thread.

ServerThread *thread2 = new ServerThread( descriptor, this );

thread2->start();

in this case. I think that i don't need to protect the variable int num. because they are in different instance, is that right?

wagmare
18th May 2009, 06:46
right ... only if u call the same thread instance concurrently and try to change its global variable u need protection ...