Wednesday, March 25, 2015

Thread safe Queue in objective C with GCD

There are several methods we can use to make a class thread safe in objective c. They are
  1. Using NSLock
  2. Using @synchronized block
  3. GCD

Among them GCD is the easiest and safest way. Because unlike other two approaches GCD manages many of exception for us and it is easy to use. Also GCD is recommended by apple over other two options.
#import "ThreadSafeQueue.h"

@interface ThreadSafeQueue()

@property (strong, nonatomic) NSMutableArray *queueData;
@property (strong, nonatomic) dispatch_queue_t dataQueue.

@end

@implementation ThreadSafeQueue

- (instancetype)init {
    if (self = [super init]) {
        _dataQueue = dispatch_queue_create("deltaaruna.ThreadSafeQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (id)dequeue {
    __block id result = nil;
    dispatch_sync(self.dataQueue, ^{ 
    if(self.queueData.count > 0) {
     result = [self.queueData[0]] 
    }
    });
    return result;
}

- (NSUInteger)length {
    __block NSUInteger result = 0;
    dispatch_sync(self.dataQueue, ^{ result = [self.queueData count] });
    return result;
}

- (void)enqueue:(id)obj {
    dispatch_barrier_async(self.dataQueue, ^{ [self.queueData addObject:obj] });
}

@end

For any query, feel free to contact me via my linkedin profile.

No comments:

Post a Comment