Saturday, November 7, 2009

Charity

Well one of my two favorite charities has started their 2009 drive. Child's Play gives toys to children's hospitals. As someone that recently spent a good deal of time in a hospital I can tell you, there is ABSOLUTELY nothing to do there except watch tv. Personally I played Civilization 4 to pass the time but not all of the kids in these hospitals have the luxury of a laptop.

So if you've a mind to make a charitable donation this holiday season please consider Child's Play for all your altruistic needs. The banner at the bottom of the page also links to their website.

On a related note if your in the Atlanta area, my other charity should start up soon too. Which is Clark's Christmas Kids, which a local radio personality Clark Howard runs. Like Child's Play Clark's Christmas Kids buys toys for children but in this case its foster children in Georgia. Christmas Kids for details of this charity.

And now stays faith, hope, charity, these three; but the greatest of these is charity. - 1 cor 13

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.