I know, this is in some way a rather religious topic, but I was interested in how to properly code C and in how to handle variables and variable-passing to functions in a clean way. After doing some research I come to the following conlcusion.
When Writing Non-Multi-Threaded Programs
Below are my personal recommendations when writing single-threaded programs (e.g. no pthreads library involved at all).
- Variables should always remain in the smallest scope possible. Every time you increase the scope, there is potentially more code which can modify your variable in an probably unintended way.
- Larger variable scopes increase complexity, especially when debugging code, since the error could be located on every line in your code.
So in terms of keeping complexity as low as possible, try to avoid global variables in your code if possible and if the design allows it.
When Writing Multi-Threaded Programs
Some basic recommendations when writing multi-threaded programs. In multi-threaded programs, threads will share all global variables and file descriptors with the parent process (see ). Therefore, they’re sometimes called “lightweight processes”. One important thing to know is, that local variables are not shared between threads – they’re local to each thread. If several threads run concurrently, there must be some protection measure in order to control access to global variables and stuff like that. Here’s the main recommendation:
- Use mutexes to protect prevent race conditions (see ) and protect access to your global variables.
Sorry, for this article beeing a bit short. I am going to extend this article, as soon as I have other findings. Anyway, comments are always welcome 🙂
Latest posts by André (see all)
- How To Configure IPSec VPN on pfSense For Use With iPhone, iPad, Android, Windows and Linux - September 14, 2014
- How to Enable Sonic Ether’s Unbelievable Shaders for Minecraft 1.7.10 - July 30, 2014
- Book Review “Crypto” - July 11, 2014