Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the equivalent of synchronized in Objective-C?

What is the equivalent of java synchronized in objective c? I want to be able to make my singleton method safe, so when it's bein called from 2 different threads, they try to use it 1 by 1.

+(MyObject*) getSharedObject
{
     if(!singleton)
     {
          singleton = [[MyObject alloc] init];
     }
     return singleton;
}
like image 569
aryaxt Avatar asked Nov 02 '10 02:11

aryaxt


People also ask

What is synchronized object?

A synchronization object is an object whose handle can be specified in one of the wait functions to coordinate the execution of multiple threads. More than one process can have a handle to the same synchronization object, making interprocess synchronization possible.

What does @synchronized do Objective C?

@synchronized is a control construct in Objective-C. It takes an object pointer as a parameter and is followed by a block of code. The object pointer acts as a lock, and only one thread is permitted within a @synchronized block with that object pointer at any given time.

What is the difference between synchronized and lock?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code.

What is synchronized keyword?

Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time.


1 Answers

Obj-C has a synchronized construct

-(MyObject*) getSharedObject
{
@synchronized(something)
{
     if(!singleton)
     {
          singleton = [[MyObject alloc] init];
     }
     return singleton;
}
}

returning from within a synchronized block does the 'right' thing

like image 143
Joshua Weinberg Avatar answered Oct 05 '22 12:10

Joshua Weinberg