Consider the following example code snippet:
void thread_function(void *);
volatile int running = 0;
pthread_t myThread;
int main () {
running =1;
pthread_create(myThread, NULL, (void *)thread_function, NULL);
/* do some stuff */
/* exit condition met */
running = 0;
pthread_join(&myThread);
/* clean up */
return 0;
}
void thread_function(void *)
{
while(running) {
/* do stuff */
}
}
I have read lots of posts regarding the volatile keyword and how it should not be used in pretty much all but memory mapped IO but, in this particular circumstance, I cannot understand how it would not perform as expected? Yes, I may get one extra iteration of the while loop (if I'm unlucky enough to get a context switch while I'm setting the 'running' variable to zero), but that doesn't matter.
Is there a good reason why I should mutex protect this variable? Is there something I've overlooked?