i know that if i were to be assigning values from multiple threads to the same location in an array (or incrementing that value, etc) that i would need to use a mutex so that the value in that part of the array would remain coherent.
(example):
for(ix = 0; ix < nx; ix++)
{
x = x_space[ix];
for(iy = 0; iy < ny; iy++)
{
y = y_space[iy];
mutex_lock[&mut];
sum = sum + f(x,y);
mutex_unlock[&mut];
}
}
but is it also necessary to use a mutex around the section of code for which threads may both be getting a value from an array?
(example):
for(ix = 0; ix < nx; ix++)
{
mutex_lock[&xmut];
x = x_space[ix];
mutex_unlock[&xmut];
for(iy = 0; iy < ny; iy++)
{
mutex_lock[&ymut];
y = y_space[iy];
mutex_unlock[&ymut];
mutex_lock[&mut];
sum = sum + f(x,y);
mutex_unlock[&mut];
}
}
No. You can think of it this way: many people can look at a glass of water at the same time, but only one at a time can take a drink.
As long as you’re just reading (to make a copy or whatever), it would be fine. However, if you’re dealing with datatypes that don’t have atomic operations (or some base datatype that isn’t doing atomic operations, for reasons of memory alignment or something) and it is possible that someone else could be writing to that memory, you could look at a piece of data in a “half changed” state, where someone else is in the middle of changing it. So you might need a mutex, depending on your situation.