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;
}
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.
@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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With