NSMutableArray Thread Concurrency with GCD

I have an NSMutableArray in a singleton "sharedStore".

It is publicly available only using methods that pass it as an NSArray. Inside the class it is

@property (nonatomic, copy) NSMutableArray *myItems;

This array is never controlled by a singleton outsider, but ViewControllers send plain messages to control this controller. Some of these messages free the array, some re-populate it, etc.

Finding myself in a situation where the array was empty in one method call and was not empty in the next, I began to implement the concurrency behavior.

Here is what I am doing so far:

In the .m file of a singleton file I have

@property (nonatomic, strong) dispatch_queue_t arrayAccessQueue;

In my singleton initializer, it is created as a sequential queue. And then every method that has something to do with mutating this array does this because of a call dispatch_sync, for example:

dispatch_sync(self.arrayAccessQueue, ^{
    [_myItems removeAllObjects];
});

This improved the situation and made my application smoother. However, I have no way to quantify that one odd behavior described above is fixed behind it. I also feel that I am in the dark with regard to any problems that may be hiding beneath the surface.

This template makes sense to me, but should I use something else like @synchronizeor NSLockor NSOperationQueue? Will it get me back to bite me?

+4
source share
3 answers

dispatch_sync , , .

, . dispatch_sync dispatch_barrier_sync . .

, , , , , .

+3

GCD dispatch_sync dispatch_barrier_async .

- (id)methodToRead {
  id __block obj = nil;
  dispatch_sync(syncQueue, ^{
     obj = <#read_Something#>;
  });
  return obj;
}

- (void) methodsForWriting:(id)obj {
   dispatch_barrier_async(syncQueue, ^{
    // write passing obj to something
  });
}

, .

+1

GCD - . "" - , : , , ..

I also mentioned that you need to make sure that you are not using a parallel queue. You should use a sequential queue, which by default matters.

0
source

All Articles