2

If I have multiple threads that might want to write to an NSMutableDictionary (i.e. setObject:forKey:) simultaneously, do I need to synchronize on the dictionary even if I can guarantee the threads will be writing different key-value pairs? If yes, can you explain how the dictionary could break?

Ben Flynn
  • 18,524
  • 20
  • 97
  • 142

1 Answers1

4

NSMutableDictionary is not thread-safe, so you need to add synchronization around concurrent writes, as well as around reads that might proceed concurrently with writes. The fact that you are writing to different keys does not help much: the implementation may resize on adding a new key, invalidating all internal storage that has been allocated before.

You may get lucky if all the keys that you are planning to write to exist in the dictionary already, and no concurrent removals are going on. However, I would strongly recommend against this approach.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523