GCD and Concurrency Programming allenlinli 9.1.13
May 10, 2015
GCD and Concurrency Programming
allenlinli 9.1.13
GCD
• Sync vs Async
Concurrency Programming
• NSThread
• NSObject
• NSOperation
• Run Loop
• GCD
Thread• What is thread
• What is multi-thread
Why Multithread on a Single Core?
•Keep UI responsive.
NSThread
NSThread
• Main thread and other threads
• detachNewThreadSelector:toTarget:withObject:
• Pro: light-weight (for code), directly control
• Cons: Life cycle issue, race condition issue (lock, retain cycle)
NSObject
• performSelectorInBackground: withObject:
What to use Thread?
• Not in most cases
NSThread
NSOperation• Pros:
• Add dependency
• setMaxConcurrentOperationCount
• re-use
• Cancel, Suspend
• Priority
• suspend
• compatible with KVO
Grand Central Dispatch
GCD
• Less memory penalty
• Less configure
• Less manage
• Simplifies the code
GCD
• GCD的核⼼心是dispatch queues
• 它管理pools of threads
• 管理queues,⽽而⾮非直接管理threads
It was first released with Mac OS X 10.6, and is also available with iOS 4 and above.
Thread pools
• Thread pools.
• Grab a thread from the pool and dispatch the task to it
• Queue the task and wait for a thread to become available.
Blocks
!
• Like a function pointer, except it also stores the context the block was created in.
• Beware of retain cycles
void (^aBlock)(int) = ^(int z) {!! NSLog(@“log”);!!};!
GCD
• Use queues of blocks rather than threads
Dispatch Queue
• Main Queue
• Global Queue
• Serial Queue
Dispatch async, sync
• dispatch_async
• dispatch_sync
Singleton (for initialisation)
static MyObject *myObject = nil;+(MyObject *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if(!myObject){ myObject = [[myObject alloc] init]; } return myObject; }
• dispatch_once
Lockless Exclusion
• Serial queue are thread safe inside
-(void)accessSharedVariableAsync:(void(^)(id sharedVariable))block{ // myQueue must be a serial queue dispatch_sync(myQueue, ^{ block([self sharedVariable]); }); }
dispatch_group
• dispatch_group_async
• dispatch_group_notify
Dispatch
• dispatch_apply
• dispatch_barrier_async
• dispatch_source_create
Deadlock
Q & A
Best Sources
• How To Use NSOperations and NSOperationQueues http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
• NSOperation vs Grand Central Dispatch
• http://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch
• Grand Central Dispatch Design Patterns by Robert Brown
• http://www.slideshare.net/robby_brown/grand-central-dispatch-design-patterns