Reputation: 5083
I have 2 scenarios where I don't know whether I should use QMutex
or not.
I have run the program without QMutex
many times & it hasn't shown me any abnormal behaviour. I have skimmed down the code here for simplicity.
But still as a safe side I would like to know whether I should use QMutex
or not?
Scenario #1:
class A : QObject
{
Q_OBJECT
private double **array;//it is initialised in the constructor & is 100x100
slots:
slot1(); //2 Qthreads are created in my main GUI thread along with 2 objects of class A, & by A aobj.movetothread();
slot2(); //& connecting these 2 slots to started() SIGNAL of respective QThread's
//I have multi-threaded my application.
}
A::slot1()
{
double temp = array[i][j];
//some operations on temp
}
A::slot2()
{
double temp = array[i][j];
//some operations on temp
}
NOTE: The contents of array[][]
are not changed after initialisation. I am only accessing the information from it in the 2 threads. However sometimes the same element from array
maybe accessed by both threads simultaneously!
Scenario #2
A::slot1()
{
double temp = somefunc();
array[0][j] = temp;
}
A::slot2()
{
double temp = somefunc();
array[50][j] = temp;
}
NOTE: In this case, the 2 threads modify elements from the same array, however they don't modify/access common elements i.e. thread1 deals with say first 50 rows while thread2 deals with next 50 rows, however they don't even access rows of each other.
Upvotes: 0
Views: 331
Reputation: 330
if those scenarios doesn't run together, you need no mutex. accessing the data for read from two of threads are ok, modifying different elements from the same array in two (or even more threads) are ok too. the cases where you need mutex is either when two thread modifies the same element from array, or if you modify same elements from one thread while reading them from another one
Upvotes: 1