consider this example (with pthreads)
Code:
Thread1
..
while(quit) {do things without using quit}
..
Thread 2
..
quit++;
..
In this very simple case one might think it is not necessary to protect quit with mutex cause a rush condition might only delay of one iteration
the exit by the while
BUT
The compiler (not testing wether quit is used by other threads) might optimize storing the value of quit once at the beginning of the loop into a register and so Thread1 might deadlock?
Would it be sufficient to declare quit volatile? (read below correction1)
Or would it be necessary the use of a pthread_mutex_lock() unlock()? Would the use of lock/unlock ensure the compiler would not do that optimization?? (read below correction2)
Code:
Correction 1
volatile int quit;
Thread1
..
while(quit) {do things without using quit}
..
Thread 2
..
quit++;
..
Code:
Correction2
Thread1
..
..lock..
quitV=quit;
..unlock..
while(quitV)
{
do things without using quit
..lock..
quitV=quit;
..unlock..
}
..
Thread 2
..
..lock..
quit++;
..unlock..
..
i guess volatile has more to deal with single-thread hardware interfacing to devices mapped in memory (where the device "plays the role of a second thread")
so i guess in a pthread context, if a correction is needed, Correction 2 is the appropriate?