thread safe nsdictionary

一曲冷凌霜 提交于 2020-01-06 15:08:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!