I have two threads, using C pthreads on linux. One of them writes data and the other is reading it. I'm using a variable to allow the read thread when is allowed to read and the write one when is allowed. So the mutex applies to this boolean variable called "newData". My question is: do I need to lock/unlock the mutex around the accesses inside the "if" condition? Both ways work, but I think just because the chances of overlapping a write/read over a this variable are very few. I show both alternatives to explain better my question:
Thread 1:
pthread_mutex_lock( &lattice_mutex );
if (!newData) {
pthread_mutex_unlock( &lattice_mutex );
uchar *lattice_pos = lattice;
int i;
for(i=0; i<size; i++) {
*lattice_pos = rand()%CHAR_MAX;
lattice_pos++;
}
pthread_mutex_lock( &lattice_mutex );
newData = TRUE;
pthread_mutex_unlock( &lattice_mutex );
} else {
pthread_mutex_unlock( &lattice_mutex );
}
Thread 2:
pthread_mutex_lock( &lattice_mutex );
if(newData) {
pthread_mutex_unlock( &lattice_mutex );
renderUpdate();
pthread_mutex_lock( &lattice_mutex );
newData = FALSE;
pthread_mutex_unlock( &lattice_mutex );
} else {
pthread_mutex_unlock( &lattice_mutex );
}
Second version, which works but I don't know if it is correct:
Thread 1:
if (!newData) {
uchar *lattice_pos = lattice;
int i;
for(i=0; i<size; i++) {
*lattice_pos = rand()%CHAR_MAX;
lattice_pos++;
}
pthread_mutex_lock( &lattice_mutex );
newData = TRUE;
pthread_mutex_unlock( &lattice_mutex );
}
Thread 2:
if(newData) {
renderUpdate();
pthread_mutex_lock( &lattice_mutex );
newData = FALSE;
pthread_mutex_unlock( &lattice_mutex );
}