美文网首页
NSMutableArray怎么保证线程安全

NSMutableArray怎么保证线程安全

作者: Crazy2015 | 来源:发表于2017-08-30 19:30 被阅读85次

    多线程去写NSMutableArray,可采用 NSLock 方式,
    简单来说就是操作前 lock 操作执行完 unlock。
    但注意,每个读写的地方都要保证用同一个 NSLock进行操作。

    NSLock *arrayLock = [[NSLock alloc] init];
    [...]
    [arrayLock lock]; // NSMutableArray isn't thread-safe
    [myMutableArray addObject:@"something"];
    [myMutableArray removeObjectAtIndex:5];
    [arrayLock unlock];

    另一种方式是利用 GCD 的 concurrent queue 来实现,个人感觉更高效。

    dispatch_queue_t concurrent_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    For read:

    • (id)objectAtIndex:(NSUInteger)index {
      __block id obj;
      dispatch_sync(self.concurrent_queue, ^{
      obj = [self.searchResult objectAtIndex:index];
      });
      return obj;
      }

    For insert:

    • (void)insertObject:(id)obj atIndex:(NSUInteger)index {
      dispatch_barrier_async(self.concurrent_queue, ^{
      [self.searchResult insertObject:obj atIndex:index];
      });
      }

    For remove:

    • (void)removeObjectAtIndex:(NSUInteger)index {
      dispatch_barrier_async(self.concurrent_queue, ^{
      [self.searchResult removeObjectAtIndex:index];
      });
      }

    转载:
    https://stackoverflow.com/questions/12098011/is-objective-cs-nsmutablearray-thread-safe/17981941#17981941
    https://hepinglaosan.github.io/2017/06/20/Thread-Safe-NSMutableArray/

    http://blog.csdn.net/kongdeqin/article/details/53171189

    https://juejin.im/entry/595ee8a76fb9a06bb47489ef

    相关文章

      网友评论

          本文标题:NSMutableArray怎么保证线程安全

          本文链接:https://www.haomeiwen.com/subject/clvxjxtx.html