0
+ (GrabClass *)grab{
    static GrabClass * ngrab = nil;

        if (ngrab==nil)
        {
            ngrab=[[GrabClass alloc]init];
        }


    return grab;
}

I used many singletons in my program. If I do it like that, however there is a chance that the grab method is called by different threads at the same time.

How to avoid it?

My current solution is to do:

+ (GrabClass *)grab{
    static GrabClass * ngrab = nil;
    [Tools DoSomethingWithSynchronize:^{
        if (ngrab==nil)
        {
            ngrab=[[GrabClass alloc]init];
        }
    }];

    return grab;
}

Where

+(void)DoSomethingWithSynchronize:(void (^)())block
{
    @synchronized (self)
    {
        [self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=[NSThread currentThread];
        [self breakIfLock]; //should not be called
        block();
        [self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=nil;
    }
}

Seems like overkill. I wonder if there's a better standard solution

user4951
  • 32,206
  • 53
  • 172
  • 282
  • 1
    possible duplicate of [Thread safe instantiation of a singleton](http://stackoverflow.com/questions/2199106/thread-safe-instantiation-of-a-singleton) – jscs Apr 18 '12 at 05:41
  • and pretty much the definitive SO post on ObjC singletons: http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – jscs Apr 18 '12 at 05:42
  • How do you find all those duplicates anyway? +1 – user4951 Apr 18 '12 at 06:25

1 Answers1

1

You could get a very good example and documentation here.

You can just use @synchronized(self) to synchronize the operations.

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55