Dispatch Queue
//1.串行队列
//1.1系统提供的主队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//1.2自定义串行队列
dispatch_queue_t serialQueue = dispatch_queue_create("com.cjnwan", DISPATCH_QUEUE_SERIAL);
//2.并行队列
//2.1系统提供的并行队列
dispatch_queue_t highGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);//高优先级
dispatch_queue_t defaultGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//默认优先级
dispatch_queue_t lowGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);//低优先级
dispatch_queue_t backGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);//后台线程
//2.2自定义并行队列
dispatch_queue_t global = dispatch_queue_create("com.cjnwan", DISPATCH_QUEUE_CONCURRENT);
dispatch_set_targte_queue
dispatch_queue_create生成的都是默认优先级的
延迟执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
Dispatch Group
dispatch_queue_t queue = dispatch_queue_create("com.cjnwan", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{// dispatch_group_async等价于dispatch_group_enter() 和 dispatch_group_leave()的组合
});
dispatch_group_async(group, queue, ^{// dispatch_group_enter() 必须运行在 dispatch_group_leave() 之前
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);//wait方式
dispatch_group_notify(group, dispatch_get_main_queue(), ^{//notify方式
});
dispatch_barrier_async
dispatch_queue_t queue = dispatch_queue_create("com.cjnwan", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
});
dispatch_async(queue, ^{
});
dispatch_barrier_async(queue, ^{
});
dispatch_async(queue, ^{
});
dispatch_async(queue, ^{
});
dispatch_sync
- 在当前的线程同步执行
dispatch_apply
dispatch_queue_t queue = dispatch_queue_create("com.cjnwan", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(10, queue, ^(size_t i) {
});//会阻塞线程
dispatch_suspend/dispatch_resume
- 挂起和恢复
Dispatch Semaphore
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_CONCURRENT, 0), ^{
//....
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
dispatch_once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});//dispatch_queue_set_specific (FMDB)
避免死锁
OSAtomic原子操作
int32_t value =0;
OSAtomicIncrement32(&value);
OSAtomicDecrement32(&value);
锁
NSLock互斥锁
NSLock lock = [[NSLock alloc]init];
if([lock tryLock]){
//...
[lock unlock];
}
NSRecursiveLock(递归锁)
NSRecursiveLock * lock = [[NSRecursiveLock alloc] init];
for(int i=0;i<10;i++){
[lock lock];
//...
[lock unlock];
}
@synchronized
@synchronized(self){
//...
}