http://stackoverflow.com/questions/28005734/making-a-class-thread-safe-in-ios
Thread safety means that the data structure can be accessed and/or modified by multiple threads without becoming corrupt.
One simple approach is to use Objective-C’s @synchronized capability.
In this case, @synchronized(self.data) around all of your accesses to the array will ensure that only a single thread can access the array at a time.
Even though length doesn’t modify the array, you still need to protect its access because another thread could potentially modify the array –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#import "SafeQueue.h" @interface SafeQueue() @property (strong, nonatomic) NSMutableArray *data; @end @implementation SafeQueue - (id)peek { @synchronized (self.data) { return [self.data firstObject]; } } - (NSUInteger)length { @synchronized(self.data) { return [self.data count]; } } - (void)enqueue:(id)datum { @synchronized(self.data) { [self.data addObject:datum]; } } // other methods omitted... @end |
Better Solution
Instead of using synchronize, we can use serial queues.
1) Create private property
get: self.privateFoo
set: self.privateFoo = someObject
2) Create custom set and get method.
1 2 3 4 5 6 7 8 9 |
// you will use self.privateFoo in these custom method -(void) setFoo:(id)object { } -(void) getFoo:(id)object { } |
Use a serial queue in there to access the private property. Get should be async. Set should be sync.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@property (nonatomic, strong) id privateFoo; - (void) setFoo:(id)object { dispatch_async([self serialQueue], ^{ [self setPrivateFoo:object]; }); } - (id) foo { __block id result = nil; dispatch_sync([self serialQueue], ^{ result = [self privateFoo]; }); return result; } |