单身螺纹安全

TBD*_*TBD 3 c# singleton-methods

我的问题是关于类功能的线程安全性.这是一些测试代码,我已经齐心协力尝试并获得更好的理解.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Singleton类的创建是安全的,但我的问题是关于ExecuteAlgorithm函数的使用.多线程使用ExecuteAlgorithm()是否安全?

我的理解是它应该没有引起任何竞争条件,因为每个创建的线程都有自己的堆栈,其中将推送本地函数变量,然后在应用程序范围的堆中创建Algorithm实例的创建.

我的理解是否正确?

Mat*_*son 5

那是正确的.您没有可访问的共享状态ExecuteAlgorithm(),因此不存在线程问题.

ExecuteAlgorithm()也许是静态的,至少就多线程安全而言.同样的道理Fibonacci().