Is this the proper way to initialise a singleton object in a thread-safe manner?

A little bit background, I am rewriting my CGIKit Web development framework for 
Objective-C and now Swift, and after the idea of building the Web application 
into a loadable bundle that either a FastCGI-speaking cgikitd or an Apache 
module mod_objc went up in smoke due to opening up serious security bugs and 
lifecycle management issues, I am going back to the path of building the Web 
application into an executable, now speaking FastCGI but not launched by the 
Web server.

I am modelling the HTTP protocol layer (CGIKit) after ASP.net and the Web layer 
(WebUIKit) after UIKit using bits and pieces from Bootstrap+jQuery (which 
itself is just a big CSS+JS file) as “controls”. However due to the fact that 
FastCGI event loop being part of the protocol some CGIApplication (analogue of 
UIApplication) have to be placed in CGIKit. UIKit’s non-atomic-ness is dropped 
and all operation have to be atomic, since Web servers are expected to process 
multiple requests at the same time.

So the first class that is required is the main application class 
CGIApplication. Being the analogue of UIApplication it is a singleton. Is this 
the proper way of doing it? I cannot use @synchronized yet because there is 
nothing to lock on:

#import <pthread.h>

pthread_mutex_t _CGI_ApplicationStartingMutex;

@implementation CGIApplication

+ (void)initialize
{
    pthread_mutex_init(&_CGI_ApplicationStartingMutex, NULL);
}

+ (instancetype)sharedApplication
{
    if (!CGIApp)
    {
        pthread_mutex_lock(&_CGI_ApplicationStartingMutex);
        if (!CGIApp)
        {
            CGIApp = [[CGIApplication alloc] init];
        }
        pthread_mutex_unlock(&_CGI_ApplicationStartingMutex);
    }
    return CGIApp;
}

@end

Attachment: smime.p7s
Description: S/MIME cryptographic signature

_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to