Question

My question regards thread safety with class functions. This is some test code i have knocked together to try and get a better understanding.

public sealed class Singleton
{  
    public static Singleton Instance { get { return _lazyInit.Value; } }

    private static readonly Lazy<Singleton> _lazyInit = new Lazy<Singleton> (() => new Singleton());

    public long ExecuteAlgorithm(int n)
    {
            n += 2;
            return new Algorithm().Fibonacci(n);
    }
}

public class Algorithm
{
    public long Fibonacci(int n)
    {
        long a = 0;
        long b = 1;

        for (long i = 0; i < n; i++)
        {
            long temp = a;
            a = b;
            b = temp + b;
        }
        return a;
    }
}

}

The creation of the class Singleton is safe, but my questions regards the use of the function ExecuteAlgorithm. Is the the use of ExecuteAlgorithm() by multiple threads safe?

My understanding is that it should be without causing any race conditions as each thread created has its own stack in which local functions variables would be pushed onto and the creation of the Algorithm instance would then be created in the heap which is application wide.

Is my understanding correct?

Was it helpful?

Solution

That is correct. You have no shared state accessible by ExecuteAlgorithm(), so there is no possibility of threading problems.

But ExecuteAlgorithm() might as well be static, at least as far as being multithread safe goes. And the same goes for Fibonacci().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top