0

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;
}
Elist
  • 5,313
  • 3
  • 35
  • 73
  • Never use `volatile` for multi-threading purposes unless you understand your CPU reordering guarantees (note that the article you linked is about embedded systems, not general x86 CPUs). Use mutexes or atomics for multi-threaded access instead. – yeputons May 30 '18 at 09:32
  • The first article you've linked to does not say anything about heap variables because there is generally no dynamic allocations on small embedded systems. If there were, there would be no difference from global variables. But, again, do not refer to articles about embedded when working with x86. – yeputons May 30 '18 at 09:36
  • Thanks, didn't think about not referring to heap on embedded systems. So, in my simple example case, since I only change each variable once in a multithreaded environment (hence no mutex needed?), can I assume the code will work as is, or should I still use atomics? – Elist May 30 '18 at 09:44
  • You should use atomics (because CPU optimizes code as well as the compiler itself, and `volatile` has no effect on that) and you should use `pthread_join` instead of that `while` loop. – yeputons May 30 '18 at 09:50
  • Off course, the `while` loop is only for demonstration. – Elist May 30 '18 at 09:51

0 Answers0