0

In Java if I have the keyword synchronized in a method, it will prevent being executed by more than one thread at same time, no matter what thread is:

public synchronized void doSomething() {
  //synchronous code here
}

In objective-c if do this, will I have the same result?

-(void)doSomething{
    @synchronized (self) {
       //synchonous code here
    }
}
1
  • 2
    You really should use GCD and a dedicated serial queue. Commented Feb 19, 2019 at 19:12

1 Answer 1

2

Yes, with a caveat.

The @synchronized directive creates a mutex lock—preventing the code within the curly brackets from being executed by different threads at the same time. The caveat is that it uses the object that was passed to it as a unique identifier to distinguish the protected block. So if you're using @synchronized(self) in two different methods, those two methods are prevented from being executed by different threads at the same time (because they share the same identifier (in this case self)).

Sign up to request clarification or add additional context in comments.

4 Comments

Ok thanks. In my case I have a method that writes in file, and it's been called from different threads. This method is inside a utility class that is used across the whole system, so if I use the @synchonized(self) inside this method I will be ok, right? Beucase is this case 'self' would be the utility class, that has an global instance in system, am I right?
@mrdc If your are writing a lot of data frequently from the different threads, you'll end up with awful performance with that model. You should likely use serial queue to do the writing. Also, how do you keep the sequence of the writes straight between threads, or does it matter? In any case, you'd likely want your threads to compose the data to be written into something immutable, and then dispatch_async() to a serial queue that does the actual write through to file.
@bbum thanks, I read about the dispatch_async but in async operation I can't control when the process will happen, so it will be difficult to the calling process to know if the file has already been written, and this is important for me because I use this file after it's been finished writing. In my tests the synchronized went good, so I think I'll go with it, anyway I'll read a little bit more about the dispatch_async.
You can always toss a barrier block on the serial queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.