NSMutableArray collection and @Synchronized blocks

假装没事ソ 提交于 2019-12-03 07:37:30

Yes, you have to synchronize read accesses to prevent them from happening simultaneously with mutations. Read accesses can safely run simultaneously with other read accesses, though.

If you have multiple readers, then it's worth investigating a read-write locking scheme. You can use pthread read-write locks (i.e. pthread_rwlock_...()).

Alternatively, you can use GCD on OS X 10.7+ and iOS 5+ with the "barrier" routines. Create a private concurrent queue. Submit all read operations to it in the normal fashion (e.g. dispatch_sync()). Submit mutation operations to it using a barrier routine such as dispatch_barrier_async(). (It can be asynchronous because you generally don't need to know that the mutation has completed before continuing. You only need to know that all reads submitted after you submit the mutation will see the results of the mutation, and the barrier guarantees that.)

You can learn more about this if you have access to the WWDC 2011 session video for Session 210 - Mastering Grand Central Dispatch.

You need to be aware that what you are doing isn't actually helping very much. For example, if your array has ten elements and you call [myObject objectAtIndex:9] while another thread calls [myObject removeObject:someObject], then chances are that the first call accesses an array element that doesn't exist anymore and throws an exception.

objectAtIndex isn't really useful if other threads can remove or insert objects.

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