Does @synchronized(self) create a block where the self prefix is unecessary on properties?
-
09-10-2019 - |
سؤال
I have read something in some foreign code and I want to check my assumption:
@synchronized(self)
is used to get rid of the self
prefix when setting a property.
So in my example below, I'm setting the strText
of the instance, not just a local variable, right?
- (void)myfunction{
NSString * strText = @"var in function";
@synchronized(self)
{
strText = @"var class (self.strText)";
}
}
المحلول
Please read this Documentation
The
@synchronized()
directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the@synchronized()
block.The
@synchronized()
directive takes as its only argument any Objective-C object, includingself
.
As Massimo Cafaro pointed out: "It’s safest to create all the mutual exclusion objects before the application becomes multithreaded, to avoid race conditions."
نصائح أخرى
@synchronized(self) is used to get rid of the self. prefix.
So in my example I set the strText not in the function I set it in the class.
Two concepts are being conflated.
@synchronized(self) { ... }
only locks the block using theself
object as the semaphore.- In Objective-C, there is nothing like a hypothetical
with
statement as in other languages that removes the need forself.whatever
to be justwhatever
. Might want to take the Stanford CS193P online course to brush up on the language.
In a multithreaded environment if more than one thread tries to access same memory address may cause a “Race Condition”, to avoid such kind of conditions you should use “Mutex Lock(Mutual Exclusion)” nothing but blocking or restricting or locking n number of threads to access same memory address or content at a same point of time and allowing only one thread at an instance of time. This can be achieved in Objective C by using @synchronized directive.
Example: Generally while implementing Singleton design pattern or class you will see some kind of code snippet like below in any iOS projects,
+(id)getSingletonInstance
{
@synchronized(self)
{
if (singletonObj == nil)
{
singletonObj = [[self alloc] init];
}
return singletonObj;
}
}