views:

83

answers:

2

Hi,

I want to write a cross-plattform wrapper for some OS specific (Linux/MacOSX/Windows) calls to get the number of cores of the CPU etc. My idea was to put all of them in single functions with static variables, so stuff like the number of cores that does not change will be processed only once.

int getNumCPUCores()
{
    static int numCores = 0;

    if(!numCores)
    {
        // The info is aquired here
    }        

    return numCores;
}

Now I wonder if this might be a bad idea, since all these static variables use up memory space whether they are initialized or not. Or did I misunderstand something?

+5  A: 

An int is a handful of bytes (four or eight on most modern platforms). Unless you have millions of static variables or static variables of some really huge type, you don't need to worry about it.

James McNellis
yes, but do watch out for that zap when you go for the door knob...
vicatcu
@vicatcu - Ultra nerdy but hilarious.
ChaosPandion
A: 

No it's fine, as James said.

Furthermore in order to avoid the need to use a mutual-exlusion object (if you plan to use it in a multi-threaded app!) you'd better have a static instance of a class that would assess the number of cores upon construction.

Poni
If I would declare the static variable (eg numCores) as static const then it would be thread-safe, right?Since this has to stay pure C.
Fabian Niemann
@Fabian Niemann: Thread safe is probably the wrong description. Given your above definition it would be possible to have multiple threads execute the code for when `!numCores` is true. However, the most obvious way of implementing this seems unlikely to cause any problems, just a little extra overhead.
torak
On a second thought you may ignore, in this case, what I've said. Why? Well, if two threads would execute the same code cocurrently nothing bad is gonna happen - the number of cores isn't going to change, and they all gonna assign to 'numCores' the same value.
Poni