If I have a piece of code like this
pthread_cond_t c;
pthread_mutex_t m;
int var = 0;
void some_function(int *some_variable)
{
pthread_mutex_lock(&m);
while(*some_variable != 123)
pthread_cond_wait(&c, &m);
pthread_mutex_unlock(&m);
// *some_variable++; (1)
}
void some_another_fun(int *some_variable)
{
pthread_mutex_lock(&m);
*some_variable = 123;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);
}
int main()
{
// run 1 thread for some_function
// and one for some_another_fun
// pass `&var` to both of them
}
Should I declare some_variable
or var
as volatile in this case? Should I declare it as volatile if (1) is uncommented (i.e. *some_variable
changes in some_function
)?
Can a compiler cache *some_variable
value in a register before executing while
and never update it again?
I don't fully understand when I should use volatile
keyword (even this answers has some contradiction and disagreements) thus this question.