I’m working on an embedded software product that decodes network video and renders it to a monitor. The application is designed to run 24×7, with up to four streams running through it at a time. I didn’t write all the code from scratch, I took it over from someone else and am now responsible for bug fixes as well as advancing the functionality. When I inherited the project, I also inherited a bug that was caused by a global variable. I had made almost a dozen releases with this bug, but it never manifested itself.
The global variable was a wrapper written around the sem_t that handled all of the initialization, destruction, etc. Someone went into an old C style source file and threw a global instance of that class to provide multi-threaded support. That might seem fine and dandy, but when unloading the library from memory, a race condition existed that wasn’t very obvious. Some functions needed to be called in the library during cleanup that relied on the semaphore. As long as that code was able to execute before the global variable was destroyed, everything worked fine.
The problem is, you have no guarantee of the destruction order of objects. So, after a bunch of problem free releases, some subtle change had caused the semaphore to be destroyed before the library finished cleaning up. The application would crash then once the library started to clean up.
I enabled core files and it became pretty obvious that the problem had to do with the semaphore. It wasn’t the most disgusting global variable problem one might encounter. I’m just so surprised that people continue to use globals so freely. I’m positive whoever put that in there did it because it was quick and easy.
There’s no reason that this C file couldn’t have been turned into a class. It would have only taken a few minutes. If this person felt that the sem_t was really needed globally to these functions, they could have used some quick regular expressions to make the proper conversions.
So, when is it okay to use a global variable? Almost never. I can’t give you an example off the top of my head because it’s almost never appropriate. If you can think of a good example, post it as a comment.