1

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.

Community
  • 1
  • 1
RileyE
  • 10,874
  • 13
  • 63
  • 106
  • 1
    Look into Grand Central Dispatch...it's a way better way to do multithreaded array logic. – borrrden Dec 12 '12 at 23:42
  • @borrrden Thanks! Thats actually how I am currently handling the mulithreaded logic. Hopefully others can see to use it too. Its great. – RileyE Dec 13 '12 at 16:55

1 Answers1

1
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.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • Okay. Thanks! I had to come up with a custom way of locking the setters and getters for thread safety, but it seems to work great. Thanks! – RileyE Dec 20 '12 at 21:09
  • I suggest to not lock the setter/getter, but to lock the block that's calls the method. – Ramy Al Zuhouri Dec 20 '12 at 21:12
  • The problem is that it comes from a singleton, so multiple classes call the setters and getters. – RileyE Dec 21 '12 at 04:27
  • Then use synchronized on that singleton instance before using setters and getters.This will not block normal operations.For example if you ask for a readonly and immutable property outside the synchronized block, this houldn't cause any problem. – Ramy Al Zuhouri Dec 21 '12 at 12:37