PDA

View Full Version : QMutex protection type??



snow_starzz
22nd November 2012, 09:30
Hi...
Im doing a multi-threading program using QThread and QMutex for synchronization. my question is.. does QMutex lock all the variable in the between of lock and unlock command?? how about function that being call in the lock range?? can any other thread use the same function or data that being access by the function?? and does pointer to the lock variable also need to take turn to access the lock variable?

sample code..
void somefunction2(int *f);
QMutex Dflag;

(thread one)
Dflag.lock;
x=3; y=4;
somefunction(j,k);
Dflag.unlock;

(thread two)
Dflag.lock;
x=y; y=45;
somefunction(j,k);
Dflag.unlock;

(thread three)
Dflag.lock;
y=*x
somefunction2(l);
Dflag.unlock;

thanks in advance..
p/s: i also do write the value of the variable in .txt using QFile.. and the command is in the lock-unlock code. it is possible to have both thread to write at the same time?? i us QDateTime to keep tracking the time i get the data..

Lesiok
22nd November 2012, 11:53
QMutex not protects variables, it suspends program/thread execution. So each call to your function is not preceded by an attempt to execute a semaphore lock, regardless of its condition.

wysota
22nd November 2012, 12:04
QMutex doesn't lock any variables. It makes sure no two threads have the mutex locked at the same time. If you want to protect some variable you have to make sure all calls to it are within critical sections protected by the same mutex.

snow_starzz
23rd November 2012, 01:37
emm.. just want to make sure.. if thread one call for "somefunction" which need to access variable j.. thread two will have to wait until thread one finish execute the function due to lock command for variable j or the function right??

wysota
23rd November 2012, 04:02
If you lock the mutex both in the function and in the other place then yes. Other than that -- no, the mutex doesn't care what is inside the critical section it protects.

anda_skoa
23rd November 2012, 15:25
emm.. just want to make sure.. if thread one call for "somefunction" which need to access variable j.. thread two will have to wait until thread one finish execute the function due to lock command for variable j or the function right??

In your sample code you always call the functions from within a locked code block, so yes, only one thread can ever be executing them with the other one waiting.

QMutex only provides you with means to make sure only one thread at a time can get past lock(). What is protected by that depends on what you as the programm do with the things accessed afterwards, i.e. you need to make sure that access to variables is always happening between lock and unlock.

Cheers,
_

snow_starzz
27th November 2012, 07:15
thanks all... i guess i have to revised back my program flow.. there are several thread that using the same global function in different lock's block but the lock is also different.. =(