线程安全的nsdictionary
我有一个 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要对 NSMutableDictionary 进行更改,并且需要以线程安全的方式完成操作,最简单的方法是使用 @synchronized 包装对该对象的所有访问 语句,它告诉编译器以线程安全、异常安全的方式锁定对对象的访问:
有
@synchronized
的更高性能替代方案,但这应该只是一个如果您分析了代码并发现同步存在问题,请关注。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: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.许多方法之一:
创建一个包含适当的锁和字典的类(具体来说,我使用用作容器的 C++ 模板)。然后根据需要包装接口。我已经为许多 CF/NS 类型完成了此操作。它大约是合理的速度。由于您正在处理集合,因此您有几个考虑因素(例如,在内容发生变化时是否保持锁定?)
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?)