Is this rule about volatile usage strict?

前端 未结 8 1793
梦毁少年i
梦毁少年i 2020-12-11 20:36

I\'ve seen this sentence:

the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 21:22

    To follow up on Mike's answer, it's useful in cases like this (global variables used to avoid complexity for this example):

    static volatile bool thread_running = true;
    
    static void thread_body() {
        while (thread_running) {
            // ...
        }
    }
    
    static void abort_thread() {
        thread_running = false;
    }
    

    Depending on how complex thread_body is, the compiler may elect to cache the value of thread_running in a register when the thread begins running, which means it will never notice if the value changes to false. volatile forces the compiler to emit code that will check the actual thread_running variable on every loop.

提交回复
热议问题