I am very new to multi-thread programming and need some pointers on this problem I am having.
I have this object which is expensive to calculate, so what I want to do is calculate it only if needed and once calculated share it with read access if another thread needs it. I only know for which inputs I need the calculations during run time.
So my basic idea was something like this
class ExpansiveDoubleCalc
{
    private:
        static double *ptr[10];
        double DoExpansiveCalc(int input)
        {
            double expansivecalc = (123.4 * input);
            return expansivecalc;
        }
    public:
        ExpansiveDoubleCalc(int input, double* output)
        {
            if(ptr[input]==NULL)
                *ptr[input] = DoExpansiveCalc(input);
            output = ptr[input];
        }
};
double * ExpansiveDoubleCalc::ptr[10]{};
Lets assume that I only need it for input <10. From my little understanding of multi-threading this has numerous problems: * the threads could try to run DoExpansiveCalc at the same time * once they get a calculated pointer to output back, it can be slow if multiple threads try to access it
Is that correct? How do I make it safe? Also, I should probably return a const pointer here right? is there a nice way to do this?
Thanks for the help!! Cheers!
 
    