Avoid copying NSMutableArray for reading with multithreaded writes

ⅰ亾dé卋堺 提交于 2019-11-29 10:52:07

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.

dasblinkenlight

The simplest approach is to use @synchronized, like this:

-(void) accessTheArray {
    MyClass *obj;
    @synchronized(theArray) {
        obj = [theArray objectAtIndex:...];
    }
    [obj someMessage];
}

EDIT: If not using ARC, you might want to retain/autorelease the object, otherwise it might be removed from the array (and released) before someMessage is called (thanks for omz for this excellent comment).

in this case, you would consider using a read/write lock. Cocoa doesn't provide them, but pthread_rwlock_t is available in pthreads interfaces -- declared in pthread.h. note that this is going to be much more efficient (for your usage) than @synchronized, or even a plain lock.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!