线程安全nsdictionary [英] thread safe nsdictionary

查看:276
本文介绍了线程安全nsdictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个nsdictionary从A LOT读取,在某些点并发写入A LOT。

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?

推荐答案

如果你有一个 NSMutableDictionary 并且需要以线程安全的方式完成操作,最简单的方法是使用 @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: ...];
}

有更高性能的替代方案 @synchronized ,但这只应该是一个问题,如果你已经剖析你的代码,并看到同步是一个问题。

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.

这篇关于线程安全nsdictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆