Last active
August 29, 2015 14:21
-
-
Save kmdarshan/3a97a175e55c72f34b2e to your computer and use it in GitHub Desktop.
Using dispatch queues instead of locks and synchronization blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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