LoginSignup
0
0

Cocoaクラスでシングルトンを作成するのに排他制御は必要でしょうか?

Last updated at Posted at 2023-10-19

はじめに

この記事ではCocoaクラスでシングルトンを作成する際に排他制御が必要なのかを考察します。
排他制御が必要かの結論を出すというのではなく、実際に排他制御が必要なのか疑問点を挙げているだけです。
ご了承ください。

Cocoaクラスでシングルトンを実装する方法として、よく次の様な実装方法が紹介されています。

#import "Singleton.h"

@implementation Singleton

static Singleton *singleton;

+ (instancetype)sharedInstance
{
    @synchronized (self)
    {
        if (!singleton)
            singleton = [Singleton new];
    }
    
    return singleton;
}

@end

上のコードは次の様に変更できます。

#import "Singleton.h"

@implementation Singleton

static Singleton *singleton;

+ (void)initialize
{
    if (!singleton)
        singleton = [Singleton new];
}

+ (instancetype)sharedInstance
{
    return singleton;
}

@end

+initializメッセージの送信はスレッドセーフになるように、すでに排他制御されています。

参考
AppleのNSObjectのリファレンスには

The runtime sends the initialize message to classes in a thread-safe manner. That is, initialize is run by the first thread to send a message to a class, and any other thread that tries to send a message to that class will block until initialize completes."

と記述されているので、リファレンスを読む限り排他制御は必要ない様に思われます。
この記事に関して間違いがあれば、ご指摘していただけると幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0