Locking an object from being accessed by multiple threads - Objective-C

后端 未结 3 1574
时光说笑
时光说笑 2020-12-12 17:40

I have a question regarding thread safety in Objective-C. I\'ve read a couple of other answers, some of the Apple documentation, and still have some doubts regarding this, s

3条回答
  •  伪装坚强ぢ
    2020-12-12 18:09

    Subclass NSMutableArray to provide locking for the accessor (read and write) methods. Something like:

    @interface MySafeMutableArray : NSMutableArray { NSRecursiveLock *lock; } @end
    
    @implementation MySafeMutableArray
    
    - (void)addObject:(id)obj {
      [self.lock lock];
      [super addObject: obj];
      [self.lock unlock];
    }
    
    // ...
    @end
    

    This approach encapsulates the locking as part of the array. Users don't need to change their calls (but may need to be aware that they could block/wait for access if the access is time critical). A significant advantage to this approach is that if you decide that you prefer not to use locks you can re-implement MySafeMutableArray to use dispatch queues - or whatever is best for your specific problem. For example, you could implement addObject as:

    - (void)addObject:(id)obj {
        dispatch_sync (self.queue, ^{ [super addObject: obj] });
    }
    

    Note: if using locks, you'll surely need NSRecursiveLock, not NSLock, because you don't know of the Objective-C implementations of addObject, etc are themselves recursive.

提交回复
热议问题