今日、私たちのコードベースでいくつかのシングルトン コードに出くわしましたが、以下がスレッドセーフかどうか確信が持てませんでした:
public static IContentStructure Sentence{
get {
return _sentence ?? (_sentence = new Sentence());
}
}
このステートメントは次と同等です。
if (_sentence != null) {
return _sentence;
}
else {
return (_sentence = new Sentence());
}
私は信じている ??単なるコンパイラのトリックであり、結果のコードはまだアトミックではありません。つまり、_sentence を新しい Sentence に設定して返す前に、2 つ以上のスレッドが _sentence が null であることを検出する可能性があります。
原子性を保証するには、そのコードをロックする必要があります。
public static IContentStructure Sentence{
get {
lock (_sentence) { return _sentence ?? (_sentence = new Sentence()); }
}
}
それはすべて正しいですか?