Skip to content

Instantly share code, notes, and snippets.

@kmdarshan
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmdarshan/3a97a175e55c72f34b2e to your computer and use it in GitHub Desktop.
Save kmdarshan/3a97a175e55c72f34b2e to your computer and use it in GitHub Desktop.
Using dispatch queues instead of locks and synchronization blocks
// feeder methods to test
self.counter = 10;
[self testThreads];
[self serialQs];
-(void) serialQs {
dispatch_queue_t dispatchQueue = dispatch_queue_create("com.darshan.learn.dispatch", DISPATCH_QUEUE_SERIAL);
__weak typeof (self) weakSelf = self;
dispatch_async(dispatchQueue, ^{
for (int i=0; i<5; i++) {
[weakSelf normalCounter];
}
});
dispatch_async(dispatchQueue, ^{
for (int i=0; i<5; i++) {
[weakSelf normalCounter];
}
});
}
-(void) testThreads {
for (int i=0; i<10; i++) {
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(decrementCounterWithLocks) object:nil];
[thread start];
}
}
-(void) normalCounter {
NSLog(@"decrement counter %d", --self.counter);
}
-(void) decrementCounter {
@synchronized(self) {
NSLog(@"decrement counter %d", --self.counter);
}
}
-(void) decrementCounterWithLocks {
NSLock *lock = [[NSLock alloc] init];
[lock tryLock];
NSLog(@"decrement counter %d", --self.counter);
[lock unlock];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment