问题
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?
回答1:
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.
回答2:
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?)
来源:https://stackoverflow.com/questions/4676275/thread-safe-nsdictionary