joels
joels

Reputation: 7721

thread safe nsdictionary

I have an nsdictionary that gets read from A LOT and at some points concurrently written to A LOT.

To help make it thread safe when iterating it, I copy it, iterate the copy, and add to the original.

Sometimes, another thread is copying it while it is being added to. Is there a better way to make it thread safe?

Upvotes: 0

Views: 2462

Answers (2)

justin
justin

Reputation: 104698

one of many approaches:

create a class which contains an appropriate lock and a dictionary (specifically, i use c++ templates which serve as containers). then wrap the interface as necessary. i've done this for many CF/NS types. it's about as fast as is reasonable. since you're dealing with collections, you have several considerations (e.g, is the lock held while the contents mutate?)

Upvotes: 0

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

If you have changes you want to make to an NSMutableDictionary and need the operations to be done in a thread-safe manner, the simplest way is to wrap all accesses on that object with the @synchronized statement, which tells the compiler to lock access to the object in a thread-safe, exception-safe fashion:

@synchronized (myDictionary) {
    [myDictionary setObject: ... forKey: ...];
    [myDictionary removeObjectForKey: ...];
}

There are higher-performance alternatives to @synchronized, but that should only be a concern if you've profiled your code and see synchronization is an issue.

Upvotes: 1

Related Questions