Avoid copying NSMutableArray for reading with multithreaded writes

前端 未结 3 1318
囚心锁ツ
囚心锁ツ 2020-12-19 12:04

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, rea

3条回答
  •  眼角桃花
    2020-12-19 12:41

    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.

提交回复
热议问题