Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

objective c - Avoid copying NSMutableArray for reading with multithreaded writes

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

The problem is that when times comes to mutate the array, reads keep coming.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...