避免复制NSMutableArray以便使用多线程写入进行读取 [英] Avoid copying NSMutableArray for reading with multithreaded writes

查看:425
本文介绍了避免复制NSMutableArray以便使用多线程写入进行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它使用一个可变数组,在大量读取后修改一次(新项目到达)。

I have a class that uses a mutable array that is modified once after a lot of reads (new items arrive).

问题是,

目前为了避免这个问题每次它读取的东西,它这样做一个副本:

Currently to avoid this issue every time it reads something it does so over a copy:

[[theArray copy] operation] //operation being indexOfObject:, objectAtIndex: objectsAtIndexes:, etc.

复制变得非常昂贵,特别是当不需要时(所有那些时候数组没有被改变)。

The copy is becoming really expensive, especially when there is no need to (all those times when the array is not being mutated).

如何锁定数组以延迟对其进行修改时的访问?

How can I lock the array to delay the access to it when is being mutated?

推荐答案

您的数组访问到串行调度队列。这将防止任何两个操作同时发生。请参阅

Put all your array accesses onto a serial dispatch queue. That will prevent any two operations from occuring at the same time. See "Eliminating Lock-based Code" in the Concurrency Programming Guide.

如果您可以要求iOS> = 4.3,您可以使用并发编程自定义队列和调度障碍的突变操作。这将允许读取同时发生,但是当需要写入时,它们将被保持直到写入完成。作为屏障提交的块基本上在并发队列上连续执行 - 它不会开始,直到所有先前的块都完成,任何后续的块也不会开始,直到屏障块完成。 (这是Justin提到的读写锁的GCD版本。)我引导你到不可思议的麦克·艾斯为这个范例

If you can require iOS >= 4.3, you can use a concurrent custom queue and dispatch barriers for the mutation operations. This will allow the reads to happen simultaneously, but when a write is necessary they'll be held up until the write finishes. The block submitted as a barrier essentially executes serially on a concurrent queue -- it will not begin until all previous blocks have finished, nor will any subsequent blocks begin until the barrier block completes. (This is the GCD version of the read-write lock that Justin mentions.) I direct you to the inimitable Mike Ash for samples of this.

这篇关于避免复制NSMutableArray以便使用多线程写入进行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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