1

Possible Duplicate:
How does @synchronized lock/unlock in Objective-C?

I have an application that creates several objects. Each of these objects is essentially running in a different thread, and operating on an NSMutableArray which is part of a separate class. There are several different methods in this class that enumerate and mutate the array, and as expected the multiple threads do not work well with this. I have tried surrounding all the method bodies in @synchronized blocks, as I read somewhere that that would lock the methods to one thread at a time, but it doesn't seem to have helped. How can I make sure that only one thread is accessing these methods at a time?

Community
  • 1
  • 1
Jumhyn
  • 6,687
  • 9
  • 48
  • 76
  • http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c – Bill Dudney Aug 09 '11 at 00:33
  • Sorry, but I still dont really understand. Could you maybe point me to a resource where I can learn more about @synchronized? – Jumhyn Aug 09 '11 at 00:45

1 Answers1

4

I can not tell this better than Apple. Take a look at section "Using the @synchronized Directive". http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html

Double-check that you are passing the same synchronization/lock object into synchronized so threads will not access the same section.

Nikita Leonov
  • 5,684
  • 31
  • 37
  • As far as I can tell, surrounding my method bodies in @synchronized should work. Am I missing something? – Jumhyn Aug 09 '11 at 01:05
  • You are right. Are you sure that you surrounded all required parts of your code with @synchronized? Could you confirm that block has the same object that they are using for locking? – Nikita Leonov Aug 09 '11 at 01:06
  • 2
    Hint: you can pass you array as a lock object. – Nikita Leonov Aug 09 '11 at 01:30