سؤال

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, including self.

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.

  1. @synchronized(self) { ... } only locks the block using the self object as the semaphore.
  2. In Objective-C, there is nothing like a hypothetical with statement as in other languages that removes the need for self.whatever to be just whatever. 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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top