0

I have two threads: Thread 1 sets a key-value-pair in a NSMutableDictionary and reads that value later and thread 2 does the same thing with another key-value-pair. The keys are different and each thread only reads the key-value-pair that it set. However, either thread can read while the other one writes.

So my question is whether I need to protect the NSMutableDictionary if two threads are accessing DIFFERENT entries of the same NSMutableDictionary at the same time? (Is the entire NSMutableDictionary "claimed" by a thread or are the operations on individual entries independent?)

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

You can't change/mutate a container object like a dictionary while also reading or writing to it from another thread.

Setting key/value pairs on a dictionary is mutating the dictionary. Each key/value pair is not an independent entity.

You must protect the dictionary or you may crash or have other undesired behavior. One simple way to do that from Objective-C is to use the @synchronized directive, and use the dictionary itself as the object passed to the directive:

@synchronized(myDict) {
   valueFromDict = myDict[@"someKey"];
}

And from another thread:

@synchronized(myDict) {
   myDict[@"someOtherKey"] = someValue;
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272