开发者

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?


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.


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?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜