Should I use 'Volatile' in following case?

133 views Asked by At

Consider that I have multiple '.c' source files in my application.

Module1.c

static char status_variable = 0;

Modify1() 
{

   status_variable = 'a';

}

Modify2() 
{

   status_variable = 'x';

}

char GetStatus()
{
   return status_variable;
}

The function Modify can be called from other .c files based on events(Not through ISR's)

Module2.C

TakeAction()
 {
    if(GetStatus() == 'a')
    {
        //do something
    }
    else 
    {
        //do something
    }

}

Now my question is do I need to declare status_variable as volatile in this case?

EDIT1:

My Application 16-bit micro-controller(RL78) ,I am not using any operating system.

EDIT2:

As some have commented,multi-threading was not at all in my mind.I have wrote down a simple non-preemptive round-robin scheduler for my application. I have no idea about multi-threading environment and what makes the variable to be volatile in that case.How it is different from my environment?If some one could elaborate it more then it would be a great help.

2

There are 2 answers

2
Eugeniu Rosca On BEST ANSWER

Since status_variable is not bound to any:

  • Memory-mapped peripheral registers
  • Global variables modified by an interrupt service routine
  • Global variables within a multi-threaded application

You are safe to skip volatile keyword in the status_variable declaration.

0
Yank Leo On

You definitely should use volatile if the modules can be run simultaneously as said by @BlueMoon93(if there is no other locking mechanism for threads). But if these modules are to run one after the other then you can safely skip the usage of volatile.