objective-ciosthread-safetysynchronizednslock

@synchronized to lock iVar and/or property?


Possible Duplicate:
What does @synchronized() do?

I have a question about what @synchronized really does and what would be best for my application.

I have an NSMutableArray that I will be mutating in background threads and accessing in foreground threads. I would love to have a slight hold on accessing the array, if it means that I can get the updated values from the background mutations, if I access the array while I'm mutating it's contents. However, I'm not 100% sure on how NSLocks and @synchronized, specifically, work.

If that's not possible, is it possible to mutate a copy of the array and when finished, lock the property/instance variable when setting it's contents that of the copy's, in order to freeze any accessor calls?

Basically, will the @synchronized(myArray) freeze any accessor calls (have the call hang until the lock lets up and then execute)?

Also, is it possible to lock an instance variable or property with an NSLock? From what I've seen, it seems to only lock blocks of code.


Solution

  • Basically, will the @synchronized(myArray) freeze any accessor calls (have the call hang 
    until the lock lets up and then execute)?
    

    No, but it will freeze your accessors if before calling any accessor, you use the synchronized directive on your array instance.
    If the thread 1 enters on a synchronized block on your array instance, and the thread 2 tries to enter in a synchronized block on the same array, it has to wait that thread 1 exits from the block.But if you use the synchronized directive on different object, then multiple threads can enter in the synchronized block.