Greeting !!
I’ve a c ap running in linux which is a POSIX multithreading application ,
In thread 1 , I set global var in this way :
Pthread_mutex_lock(&Mutex1);
for(idx=0;idx<1000;idx++)
{
Data1[idx].doubleval = idx * 100.0 * anothervar ;
}//for
Pthread_mutex_unlock(&Mutex1);
in thread2 , I get global var it in this way :
Pthread_mutex_lock(&Mutex1);
for(idx=0;idx<1000;idx++)
{
doublexxx = Data1[idx].doubleval ;
DoSomething(doublexxx) ;
}//for
Pthread_mutex_unlock(&Mutex1);
Now , suppose I don’t want to use Mutex in my ap , if thread1 is setting Data1[33].doubleval while thread2 is reading Data1[33].doubleval , will Data1[33].doubleval be a very strange value ? I mean , for example , double var has 4 bytes , while thread1 is setting Data1[33].doubleval first 2 bytes , not finish later 2 bytes , at this monent
thread2 is trying to read Data1[33].doubleval ….is it possible ?
If it is possible , how can I do to protect a double var without this kind of problem ?
Mutex is great to use , I just wonder if there is another way to protect a double var
which thread1 is writing in it , at least thread2 try to read from the same var
will wait that 4 bytes double var finished !!!
Whether or not it’s possible to read a “partially written” value depends on a large number of factors (e.g. target system and alignment) and is definitely not portable. For an example, imagine this code running on a 16-bit CPU with floating point support emulated in software.
Even with a mutex, the second thread’s behaviour will still be undefined because it won’t know if it has read data before the first thread wrote it or after the first thread wrote it.
I suspect that there’s higher level problems with your design – perhaps you should be using a condition variable to make the second thread wait until the first thread has written.
I also suspect that the reason you’re asking about removing the mutex is to improve scalability/performance. For example, so that one thread to use one part of the array while a different thread modifies a completely different part of the same array. If this is the reason behind your question, then the solution depends on your scenario – it could be as simple as using multiple locks (one mutex per area of the array, up to one mutex per entry), but might mean implementing a “reader/writer” lock (so that multiple threads are allowed to read from the array at the same time, as long as no other thread is writing).