线程安全的nsdictionary

发布于 2024-10-11 10:33:43 字数 135 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-10-18 10:33:44

如果您想要对 NSMutableDictionary 进行更改,并且需要以线程安全的方式完成操作,最简单的方法是使用 @synchronized 包装对该对象的所有访问 语句,它告诉编译器以线程安全、异常安全的方式锁定对对象的访问:

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

@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:

@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.

⒈起吃苦の倖褔 2024-10-18 10:33:44

许多方法之一:

创建一个包含适当的锁和字典的类(具体来说,我使用用作容器的 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?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文