Re:Global variables are bad (2013)
by droidist2 on Thursday July 26, 2018 @02:37AM
(#17615475)
It's fine as long as the variables aren't mutable. Shared mutable state is the real killer.
[ Parent
| on HN ]
I still have a hard time being dogmatic about this. For some simple multithreaded apps I'll use a global "STOP" variable, which I mutate when shutting down. All of the functions check this before attempting to gracefully exit.
I've done alternatives and I've never really seen the benefit.
The threads could take a pointer/reference to the "stop variable" and use the reference instead of accessing the global variable directly. That allows you to mitigate many problems of global variables. Sorry, if you already do this.
Honest question but what do I really gain in this scenario? Now all worker function arguments are N+1. I feel like it’s the waterbed affect and the complexity is simply pushed around elsewhere.
It seems like there’s simply a reasonable cognative “maximum” of global before it becomes unworkable. My gut tells me it’s between 1 and 4.
Gain? You could pass different pointers to each worker function, giving you a way to partially shutdown your process, or to shutdown some workers first, and workers they depend on later.
Of course, if you don’t need that, it’s not a gain, and a global is fine.
Globals also are fine if you are resource constrained (e.g. if you have a few kilobytes of RAM or even less) Getting your code running in it may trump everything else.
I think the main benefit is that every function relying on the stop variable is clearly defined as such, as opposed to having to find out manually who is reliant on it based on usage; its not so much moving complexit around as it is making things more explicit. im not sure how useful this is in practice though, for the common case
For one thing, you immediately make that function unit-testable.
Re:Global variables are bad (2013)
by red75prime on Thursday July 26, 2018 @03:11AM
(#17615629)
Then you want to make a library out of it and are stuck with a single stop-domain.