多线程

608 阅读1分钟

1. GCD

  • 同步/异步 串行/并发
  • dispatch_barrier_async
  • dispatch_group
主队列引起的循环等待(主队列当中提交的任务,不论是同步/异步,都会在主线程中执行)
-(void)viewDidLoad {
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self doSomething];
    });
}

-(void)viewDidLoad {
    dispatch_sync(serialQueue, ^{
        [self doSomething];
    });
}
子线程默认不开启RunLoop,performSelector:withObject:afterDelay:不执行
-(void)viewDidLoad {
    dispatch_async(global_queue, ^{
        NSLoag(@"1");
        [self performSelector:@selector(printLog)
              withObjec:nil
              afterDelay:0];
        NSLog(@"3")
    });
}

-(void)printLog {
    NSLog(@"2")
}

dispatch_barrier_async()

利用GCD实现多读单写
@interface UserCenter()
{
    dispatch_queue_t concurrent_queue;
    NSMutableDictionary *userCenterDic;
}
@end

@implementation UserCenter 

- (id)init 
{
    self = [super init];
    if (self) {
        concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
        userCenterDic = [NSMutableDictionary dictionary];
    }
    
    return self;
}

- (id)objectForKey:(NSString *)key 
{
    __block id obj;
    dispatch_sync(concurrent_queue, ^{
        obj = [userCeneterDic objectForKey:key];
    });
    
    return obj;
}

- (void)setObject:(id)obj forKey:(NSString *)key 
{
    dispatch_barrier_async(concurrent_queue, ^{
        [userCenterDic setObject:obj, forKey:key];
    });
}

@end

dispatch_group_async()

@interface GroupObject()
{
    dispatch_queue_t concurrent_queue;
    NSMutableArray <NSURL *> *urlArr;
}
@end

@implementation GroupObject

- (id)init 
{
    self = [super init];
    if (self) {
        concurrent_queue = dispatch_queue_create("concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
        urlArr = [NSMutableArray array];
    }
    
    return self;
}

- (void)handle
{
    dispatch_group_t group = dispatch_group_create();
    
    for (NSURL *url in urlArr) {
        dispatch_group_async(group, concurrent_queue, ^{
            NSLog(@"url is %@", url);
        });
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"完成");
    })
}

@end

2、NSOperation

  • 添加任务依赖
  • 任务执行状态的控制
  • 最大并发量
任务执行状态
  • isReady
  • isExecuting
  • isFinished
  • isCancelled
状态控制

重写main方法,地城控制变更任务及执行完成状态,以及任务退出 重写start方法,自行控制任务状态

系统通过KVO移除isFinished = YES的NSOperation

3、NSThread

4、多线程与锁

  • NSRecursiveLock
  • NSLock
  • dispatch_semaphore_t
  1. @synchronized 一般在创建单例对象的时候使用
  2. atomic 属性关键字,对被修饰对象进行原子操作
  3. OSSpinLock 自旋锁 循环等待,不释放当前资源;轻量级数据访问
dispatch_semaphore_t
  • dispatch_semaphore_create(1);
  • dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  • dispatch_semaphore_signal(semaphore);
dispatch_semaphore_create()
struct semaphore {
    int value;
    List<thread>;
}

dispatch_semaphore_wait()
{
    S.value = S.value - 1;
    if S.value < 0 then Block(S.List); => 阻塞线程
}

dispatch_semaphore_signal()
{
    S.value = S.value + 1;
    if S.value <= 0 then wakeup(S.List);
}