PDA

View Full Version : synchronize threads



weixj2003ld
9th April 2009, 14:37
I create two threads,and they share class A;


class A
{
public:
void method_1()
{
QMutexLocker locker(&mutex);
......
method_2();
......
}
void method_2()
{
QMutexLocker locker(&mutex);//Does this code need?
........
}
public:
mutable QMutex mutex;

}

I do not know the second locker is need or not,please please tell me.

caduel
9th April 2009, 15:53
That depends on whether the code in method_2 is allowed to be executed when method_1 is executed.

Basically:
* if the things should not be executed at the same time, you must guard them with a QMutex:
* if it is ok that one thread is in method_1 and the other in method_2, you can guard them with 2 separate QMutexes (which will reduce blocking).

So:
+ if no 2 threads should execute method_1 at the same time: define a QMutex and put a lock inside method_1
+ if no 2 threads should execute method_2 at the same time (without regarding method_1): define a (different) QMutex and put a lock inside method_2
+ if no 2 threads should execute any methods of your class in parallel (because all methods might access the same data): define a common QMutex and lock it in all methods.

HTH

weixj2003ld
10th April 2009, 02:22
whether a method(in the shared class) needs to synchronize or not depending on the data visited by the method.For example (class A is shared by multi_threads):
1.method_1 like this does not need to synchronize.


void method_1()
{
int varable1;
varable1=a.varable1//only read varable1,not write varable1
}

2.method_1 like this needs to synchronize.


void method_1()
{
int varable1;
caculate(varable1);
a.varable1=varable1;//write varable1
}

Am I right or not?

wysota
10th April 2009, 07:08
Please read some books or articles about multithreading. Your questions have nothing to do with Qt and you can't ask us each time you are wondering if you should protect some piece of data with a mutex. I can give you a hint that a general rule of a thumb is that if a variable (or some other piece of data) can be accessed simoultaneously by more than one thread, you need to make sure there is no situation where one thread tries to read the data when the other changes it or when more than one thread tries to modify the variable. There are classes in Qt that help you do that - QMutex, QReadWriteLock, QWaitCondition, QSemaphore. You have the docs -- please read it.