Objective-C: @ synchronized optimal use

I was wondering if I have an object that needs to be synchronized, and it is present in several (2-3) places in the code block, is it better (faster) to add @ synchronized to the whole block or just before each occurrence of the object?

@synchronized (someObj) { [someObj removeAllObjects]; } .. @synchronized (someObj) { [someObj addObject:[NSNumber numberWithInt:203]]; } 

VS

 @synchronized (someObj) { [someObj removeAllObjects]; ... (potential a large block of code) [someObj addObject:[NSNumber numberWithInt:203]]; ... (potential a large block of code) } 

Any thoughts on this?

+4
source share
2 answers

What Jeremip said is true. There are other things to consider. If the first code fragment will work for you, then we can conclude that you are not interested in any intermediate states during (long block of code). (i.e. you are not reading from this array outside the @synchronized block, are you?) In this case, it would be better for you to perform operations that need to be synchronized and do them all at once. For instance:

 .. id objectToAdd = [NSNumber numberWithInt: 203]; .. @synchronized (someObj) { [someObj removeAllObjects] [someObj addObject:objectToAdd]; } 

Put in general: Concurrency, and performance will improve by reducing how many times you take a lock, and how long you hold it, holding it when you take it. In this trivial example, there is nothing that indicates that we could not take this lock once, not twice, and, in addition, there was no indication that we could not perform operations such as stated above, explicitly storing all code that does not require synchronization, outside the synchronized block.

It says, "Make it work, do it right, make it work fast." - in this sequence. I would not spend much time / energy optimizing your lockout strategy until you measure your application and see that a lock conflict is a problem.

+13
source

Any thoughts on this?

Yes.

You can only find out by performance analysis, i.e. its measurement.

Obviously, releasing and re-locking the lock is a performance hit, but remember that all the code in the block is effectively single-threaded. Thus, on multiprocessor / host machines, you lose the advantage of having multiple cores and multiple threads if two threads try to execute the same synchronized block.

Having said the above, my instinct would be to switch to a few small fragmented blocks. In fact, in the example you are giving, I would make the -removeAllObjects and -addObject: methods synchronized, rather than trying to remember them inside the synchronized blocks in the calling methods all the time.

+6
source

Source: https://habr.com/ru/post/1347250/


All Articles