多线程信号量dispatch_semaphore

dispatch_semaphore是线程调度的一种方式主要方法


dispatch_semaphore_t sem = dispatch_semaphore_create(0);
//创建信号量 

dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, DISPATCH_TIME_FOREVER)
//线程等待 如果sem 初始为0 则需要等待  dispatch_semaphore_create(1)则不需要

 dispatch_semaphore_signal(sem);
//信号量自增 相当于+1 不过进行自增信号会增加 将sem打印会发现 sem还是1 

long signalValue = dispatch_semaphore_signal(sem);
           
NSLog(@"%ld",signalValue);
//sem 信号量可以增加或减少n个  但long值为0到1
//根据其阻塞进程的特性可以进行生产消费模式等

多线程和数据库


 dispatch_queue_t queue = dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_HIGH , 0 ) ;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create (0) ;
    __block FMDBUserModel * model = [[FMDBUserModel alloc] init];
    dispatch_async(queue, ^{
        [[FMDatabase sharedInstance]inDatabase:^(FMDatabase *db) {
            FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM User WHERE userName = ?"] withArgumentsInArray:@[[SSKeychain login]]];
            if (rs == nil) {
                FMDBLogLastError(db);
                return;
            }
            if ([rs next]) {
                FMDBUserModel * userModel = [FMDBUserModel yy_modelWithDictionary:rs.resultDictionary.mutableCopy];
                model = userModel;
                dispatch_semaphore_signal (semaphore) ;
            }
            else{
                return;
            }
            
            @onExit {
                [rs close];
            };
        }];
        
    });
    dispatch_semaphore_wait (semaphore,DISPATCH_TIME_FOREVER) ;
   进行更新操作

你可能感兴趣的:(多线程信号量dispatch_semaphore)