Hacker News new | ask | show | jobs
by ridiculous_fish 3956 days ago
Barriers are for ordering as you say, which is important, but orthogonal to volatile. Volatile is about enforcing that a particular access occurs.

An illustration:

    static volatile sig_atomic_t interrupted = 0;
    void sigint_handler(int s) { interrupted = 1; }

    void run()
    {
        signal(SIGINT, sigint_handler);
        for (;;)
        {
           if (interrupted) break;
           stuff();
        }
    }
"volatile" is the most precise way to prevent the compiler from hoisting the 'interrupted' access out of the loop. Memory barriers aren't necessary, because the code is single threaded. They may effectively defeat the optimization too, but it's by confusing the compiler instead of informing it.

edit: Oh, and std::atomic is a very bad solution to the above. std::atomic may take locks, which can lead to a deadlock if used in a signal handler!

1 comments

The way I think of it is that volatile is for making sure the instructions are there and in the right order in the instruction stream. You may need to do other things to get around the processor's side of optimizations like store queues and caches depending on the context.