user3278468
user3278468

Reputation: 25

Should I use volatile c++?

Please look at following sample code. FuncA runs forever during object lifetime due to while(1). Let's say code hits "CondB" for quite very long time ( 24 hours) or more. which means "curr_status" in funcB will not change during that time. Is it possible that optimization can kick in and never checks for updated value of "curr_status" after that ? Should I use volatile here?

void funcB(string curr_status){
    static string prev_status = "123";
    if(prev_status != curr_status){
        //do sometthing
        prev_status = curr_status;
    }
}

void funcA(){
    while(1){
        if(condA)
            funcB("123");
        if(condB)
            funcB("xyz");
    }
}

Upvotes: 0

Views: 123

Answers (3)

doron
doron

Reputation: 28932

volatile is needed for memory that may change by actors outside the scope of the running thread. This may occur when sharing memory between thread or processes or when writing directly to peripherals.

You are running in a single thread and writing to normal RAM so there is no fear that the compiler might optimize out your check.

As an aside, when doing multithreading, once should either use proper locking or atomics and when accessing peripheral memory, linux recommends using readl and writel that are implemented in assembler rather than volatile

Upvotes: -1

Baum mit Augen
Baum mit Augen

Reputation: 50111

Is it possible that optimization can kick in and never checks for updated value of "curr_status" after that?

No. Optimization may not change the observable behavior of your program (RVO and calls to potentially overwritten operator new aside). You don't need volatile here.

This is known as the as-if rule.

Upvotes: 4

user2100815
user2100815

Reputation:

No, the compiler has no idea if or when the parameter will change, and so will always read it.

Upvotes: 1

Related Questions