I have read in several places that the volatile
keyword should be used on:
Global variables accessed by multiple tasks within a multi-threaded application
I want to make sure I get it right - if I have a heap allocated variable, say a struct holding an integer, should I also use volatile
or should it be considered as non-global variable?
And if only global variables should be declared volatile
, why is the difference?
Simple Example:
struct my_struct
{
int still_running;
int keep_running; // should it be declared 'int volatile'?
};
typedef struct my_struct *my_struct_t;
static void *my_thread_func(void *v)
{
my_struct_t s = (my_struct_t) v;
do
{
printf("thread still running.\n");
} while (s->keep_running);
printf("thread stopping.\n");
s->still_running = 0;
return NULL;
}
int main(int argc, char **argv)
{
my_struct_t s = (my_struct_t)malloc(sizeof(struct my_struct));
s->keep_running = 1;
s->still_running = 1;
pthread_t t;
pthread_create(&t, NULL, my_thread_func, s);
usleep(1000);
s->keep_running = 0;
while(s->still_running);
free(s);
return 0;
}