Monday, November 2, 2009

Volatile the unpredictable keyword

Some time back I talked about static being a rarely used keyword of C. Today we are learning about Volatile which is even less used. However when you need volatile you generally cannot do without it. Volatile comes into play in two situations that I have encountered; Multi-threaded programming and dealing with hardware directly.

So what does the keyword do? It actually tells the compiler to not optimize access to a variable in a specific way. One of the biggest things an optimizing compiler tries do is keep often referenced variables in registers. However this means that if the value is changed in memory by something outside the current thread of control you can never tell when the change will be picked up.

By declaring the variable volatile you basically turn that behavior off. The compiler will load the value from memory every time it is referenced; There by picking up on changes made outside the current thread. Now the compiler makes this optimization for good reason. So using volatile incurs a speed penalty and you must use it judiciously.

In particular a guy at work had this problem recently. He was using a global variable to control when a thread exited. Something like:

int keep_going = true;

void thread(void) {
   while(keep_going) {
      ....do stuff
   } //end while
} //end thread
He had a problem that his main thread would set keep_going to false in an attempt to stop the thread. However the compiler had determined that keep_going was a lively variable and kept it entirely in the register. So the thread would never exit because the program was not reading the updated value from memory. When he described the problem to me I told him, basically what I've said about volatile and told him to use it. So theres another of C's more esoteric keywords explained.

No comments:

Post a Comment