iOS多线程读写安全

读写操作一般都是比较耗时的操作,为了保证读写安全,同时提升性能,一般采取“多读单写”模式.即对同一资源,同一时间,保证以下状态:

  • 只能有一个写操作

  • 或者多个读操作

  • 读、写两种操作不能同时进行

iOS大概有三种方式可以实现读写安全:

1. automic

automic 用于保证属性setter(写)、getter(读)的原子性操作, 相当于在settergetter方法中添加了线程同步锁.

参考objc4objc-accessors.mm源码

  • setter方法:
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
    if (offset == 0) {
        object_setClass(self, newValue);
        return;
    }

    id oldValue;
    id *slot = (id*) ((char*)self + offset);

    if (copy) {
        newValue = [newValue copyWithZone:nil];
    } else if (mutableCopy) {
        newValue = [newValue mutableCopyWithZone:nil];
    } else {
        if (*slot == newValue) return;
        newValue = objc_retain(newValue);
    }

    if (!atomic) {
        oldValue = *slot;
        *slot = newValue;
    } else {
        spinlock_t& slotlock = PropertyLocks[slot];
        slotlock.lock();
        oldValue = *slot;
        *slot = newValue;        
        slotlock.unlock();
    }

    objc_release(oldValue);
}
  • getter方法:
id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) {
    if (offset == 0) {
        return object_getClass(self);
    }

    // Retain release world
    id *slot = (id*) ((char*)self + offset);
    if (!atomic) return *slot;
        
    // Atomic retain release world
    spinlock_t& slotlock = PropertyLocks[slot];
    slotlock.lock();
    id value = objc_retain(*slot);
    slotlock.unlock();
    
    // for performance, we (safely) issue the autorelease OUTSIDE of the spinlock.
    return objc_autoreleaseReturnValue(value);
}

note: automic 原子操作,保证setter和getter操作的原子性,内部通过加锁来实现

2.读写锁

iOS中pthread_rwlock(读写锁)刚好可以满足这种场景. 读写锁有两种模式,阻塞式(xxx_xxlock. 加锁不成功,本线程阻塞等待)和非阻塞式(xxx_tryxxlock. 加锁不成功,本函数失败返回)

等待锁的线程会进入休眠


//初始化锁 - 初始化完成后, 是非锁定状态
pthread_rwlock_t lock;
//动态初始化
pthread_rwlock_init(&lock, NULL);
//静态初始化 
PTHREASD_RWLOCK_INITIALIZER

//读-加锁 返回0表示成功 
pthread_rwlock_rdlock(&lock);
//读-尝试加锁 返回0表示成功 
pthread_rwlock_tryrdlock(&lock);

//写-加锁 返回0表示成功 
pthread_rwlock_wrdlock(&lock);
//写-尝试加锁 返回0表示成功 
pthread_rwlock_trywrlock(&lock);

//解锁
pthread_rwlock_unlock(&lock);
//销毁
pthread_rwlock_destroy(&lock);

example:


#import <pthread.h>
@property (assign, nonatomic) pthread_rwlock_t lock;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化锁
    pthread_rwlock_init(&_lock, NULL);
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    for (int i = 0; i < 10; i++) {
        dispatch_async(queue, ^{
            [self read];
        });
        dispatch_async(queue, ^{
            [self write];
        });
    }
}

- (void)read {
    pthread_rwlock_rdlock(&_lock);
    
    sleep(1);
    NSLog(@"%s", __func__);
    
    pthread_rwlock_unlock(&_lock);
}

- (void)write {
    pthread_rwlock_wrlock(&_lock);
    
    sleep(1);
    NSLog(@"%s", __func__);
    
    pthread_rwlock_unlock(&_lock);
}

- (void)dealloc {
    pthread_rwlock_destroy(&_lock);
}

3.线程+栅栏

  • GCD

使用dispatch_barrier_async, 传入的队列必须是dispatch_queue_cretate创建的并发队列 (FMDB使用串行队列保证读写安全,但是读操作也是串行执行,似乎...)

example:

// 初始化队列
dispatch_queue_t queue = dispatch_queue_create("rw_queue", DISPATCH_QUEUE_CONCURRENT);
// 读
dispatch_async(self.queue, ^{
    [self read];
});
// 写
dispatch_barrier_async(self.queue, ^{
    [self write];
});

  • NSOperationQueue

串行队列可以保证写操作的安全-串行执行,并发队列可以实现读操作的高效-并行执行.

一个NSOperationQueue可以满足这两种要求,只需切换maxConcurrentOperationCount即可切换这两种模式.

同时为了满足读写互斥,还需添加栅栏或依赖. 具体,NSOperationQueue iOS13开始添加了栅栏操作:- (void)addBarrierBlock:(void (^)(void))barrier API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));,使用栅栏比较简单一些, iOS13以下系统需要通过添加依赖实现该功能.

example:


@interface DataModel : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic)NSInteger count;
@end

@implementation DataModel

- (NSString *)description
{
    return [NSString stringWithFormat:@"You Have %ld %@ !", (long)self.count, self.name];
}
@end


/*NSOperation+RW.h*/
typedef enum : NSUInteger {
    OperationUnKnow  = 0,
    OperationRead    = 1,
    OperationWrite   = 2,
    OperationToRead  = 3,
    OperationToWrite = 4,
} OpereationFlag;

@interface NSOperation (RW)
@property(nonatomic)OpereationFlag flag;
@end


/*NSOperation+RW.m*/
static void *OperationReadWriteFlagKey = &OperationReadWriteFlagKey;

@implementation NSOperation (RW)
-(void)setFlag:(OpereationFlag)flag{
    objc_setAssociatedObject(self, OperationReadWriteFlagKey, @(flag), OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (OpereationFlag)flag{
    id flag = objc_getAssociatedObject(self, OperationReadWriteFlagKey);
    return (OpereationFlag)[flag integerValue];
}

@end



/*DataBaseHandler.m*/

- (void)readDataWithQuery:(nonnull NSString *)query parameter:(id _Nullable)param result:(nonnull DBResultBlock)result {
    [self appendTaskWith:query parameter:param result:result read:YES];
}

- (void)updateDataWithQuery:(nonnull NSString *)query parameter:(id _Nullable)param result:(nonnull DBResultBlock)result {
    [self appendTaskWith:query parameter:param result:result read:NO];
}

-(void)appendTaskWith:(nonnull NSString *)query parameter:(id _Nullable)param result:(nonnull DBResultBlock)result read:(BOOL)read{
    __weak typeof(self) weakSelf = self;
    NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        if (read) {
            sleep(2);
        }else{
            if ([param isKindOfClass:[NSDictionary class]]) {
                [weakSelf.model setValuesForKeysWithDictionary:param];
            }
            sleep(1);
        }
        result(weakSelf.model.description);
    }];
    if (read) {
        operation.flag = OperationRead;
    }else{
        operation.flag = OperationWrite;
    }

    NSLog(@"**********************");
    
    static BOOL log = NO;
    
    NSOperation *lastOperation = [[self.readWriteQueue operations] lastObject];
    if (@available(iOS 13.0, *)) {
    //使用栅栏操作比较简单
        if (read) {
            if (lastOperation) {
                if (lastOperation.flag==OperationRead) {
                    [self.readWriteQueue addOperation: operation];
                }else{
                    [self.readWriteQueue addBarrierBlock:^{
                        weakSelf.readWriteQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
                    }];
                    [self.readWriteQueue addOperation:operation];
                }
            }else{
                self.readWriteQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
                [self.readWriteQueue addOperation:operation];
            }
            
        }else{
            if (lastOperation) {
                if (lastOperation.flag==OperationWrite) {
                    [self.readWriteQueue addOperation: operation];
                }else{
                    [self.readWriteQueue addBarrierBlock:^{
                        weakSelf.readWriteQueue.maxConcurrentOperationCount = 1;
                    }];
                    [self.readWriteQueue addOperation:operation];
                }
            }else{
                self.readWriteQueue.maxConcurrentOperationCount = 1;
                [self.readWriteQueue addOperation:operation];
            }
        }
    }else{
        /*
         连续的读操都需要依赖前边最接近的to-read-barrier,
         to-read-barrier 依赖前边最后一个写操作
   
         写操作前后依赖, 第一个依赖前边最近的to-write-barrier, 
         to-write-barrier 依赖前边最近的连续的读操作
         **/
        
        if (read) {
            if (lastOperation) {
                if (lastOperation.flag==OperationRead) {
                    NSOperation *operatonObj = nil;
                    NSArray *operations = [self.readWriteQueue.operations copy];
                    NSInteger count = self.readWriteQueue.operations.count;
                    for (int i = 0; i < count -1; i++) {
                        NSOperation *obj = [operations objectAtIndex:count - 1 - i];
                        if (obj.flag==OperationToRead&&!obj.finished&&!obj.cancelled) {
                            operatonObj = obj;
                            break;
                        }
                    }
                    if (operatonObj) {
                        if (log) {
                            NSLog(@"R依赖TR");
                        }
                        [operation addDependency:operatonObj];
                    }
                    if (log) {
                        NSLog(@"添加了R");
                    }
                    [self.readWriteQueue addOperation: operation];
                }else if(lastOperation.flag==OperationWrite){
                    NSOperation *toReadBarrier = [NSBlockOperation blockOperationWithBlock:^{
                    }];
                    [toReadBarrier setCompletionBlock:^{
                        weakSelf.readWriteQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
                    }];
                    toReadBarrier.flag = OperationToRead;
                    [toReadBarrier addDependency:lastOperation];
                    [operation addDependency:toReadBarrier];
                    if (log) {
                        NSLog(@"TR依赖W");
                        NSLog(@"R依赖TR");
                        NSLog(@"添加了TR");
                        NSLog(@"添加了R");
                    }
                    
                    [self.readWriteQueue addOperation:toReadBarrier];
                    [self.readWriteQueue addOperation:operation];
                }
            }else{
                if (log) {
                    NSLog(@"添加了R");
                }
                
                self.readWriteQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
                [self.readWriteQueue addOperation:operation];
            }
        }else{
            if (lastOperation) {
                if (lastOperation.flag==OperationWrite) {
                    if (log) {
                        NSLog(@"W依赖W");
                        NSLog(@"添加了W");
                    }
                    
                    [operation addDependency:lastOperation];
                    [self.readWriteQueue addOperation:operation];
                }else if(lastOperation.flag==OperationRead){
                    NSOperation *toWriteBarrier = [NSBlockOperation blockOperationWithBlock:^{
//                        NSLog(@"toWriteBarrier");
                    }];
                    [toWriteBarrier setCompletionBlock:^{
                        weakSelf.readWriteQueue.maxConcurrentOperationCount = 1;
                    }];
                    toWriteBarrier.flag = OperationToWrite;
                    NSArray *operations = [self.readWriteQueue.operations copy];
                    NSInteger count = self.readWriteQueue.operations.count;
                    for (int i = 0; i < count - 1; i++) {
                      NSOperation *operatonObj = [operations objectAtIndex:count - 1 - i];
                      if (operatonObj.flag==OperationRead) {
                          if (!operation.cancelled&&!operation.isFinished) {
                              [toWriteBarrier addDependency:operatonObj];
                              if (log) {
                                  NSLog(@"TW依赖R");
                              }
                          }
                      }else{
                          break;
                      }
                    }
                    if (log) {
                        NSLog(@"W依赖TW");
                        NSLog(@"添加了TW");
                        NSLog(@"添加了W");
                    }
                   
                    [operation addDependency:toWriteBarrier];
                    [self.readWriteQueue addOperation:toWriteBarrier];
                    [self.readWriteQueue addOperation:operation];
                }
            }else{
                self.readWriteQueue.maxConcurrentOperationCount = 1;
                [self.readWriteQueue addOperation:operation];
                if (log) {
                    NSLog(@"添加了W");
                }
            }
        }
    }
}

@end

测试:

/*in test place*/
-(void)testReadWriteSingleQueue{
    id<DataBaseHandlerDelegate> db = [DataBaseRWQueueHandler shareHandler];
    id apple = @{@"name": @"Apple", @"count": @2};
    id orange = @{@"name": @"Orange", @"count":@10};
    id peach = @{@"name": @"Peach", @"count":@10};
    id grape = @{@"name": @"Grape", @"count":@20};
    
    BOOL log = YES;
    [db updateDataWithQuery:@"" parameter:apple result:^(id  _Nonnull result) {
        if (log) {NSLog(@"write1: %@", result);}
    }];
    [db readDataWithQuery:@"" parameter:nil result:^(id  _Nonnull result) {
        if (log) {NSLog(@"read1: %@", result);}
    }];
    [db updateDataWithQuery:@"" parameter:orange result:^(id  _Nonnull result) {
        if (log) {NSLog(@"write2: %@", result);}
    }];
    
    [db readDataWithQuery:@"" parameter:nil result:^(id  _Nonnull result) {
        if (log) {NSLog(@"read2: %@", result);}
    }];
    
    [db updateDataWithQuery:@"" parameter:peach result:^(id  _Nonnull result) {
        if (log) {NSLog(@"write3: %@", result);}
    }];
    [db updateDataWithQuery:@"" parameter:grape result:^(id  _Nonnull result) {
        if (log) {NSLog(@"write4: %@", result);}
    }];
    
    [db readDataWithQuery:@"" parameter:nil result:^(id  _Nonnull result) {
        if (log) {NSLog(@"read3: %@", result);}
    }];
    [db readDataWithQuery:@"" parameter:nil result:^(id  _Nonnull result) {
        if (log) {NSLog(@"read4: %@", result);}
    }];
    
}

/*
打印:

2020-03-14 17:27:09.101971+0800 Basic_iOS[48718:1193248] write1: You Have 2 Apple !
2020-03-14 17:27:11.103866+0800 Basic_iOS[48718:1193248] read1: You Have 2 Apple !
2020-03-14 17:27:12.107587+0800 Basic_iOS[48718:1193248] write2: You Have 10 Orange !
2020-03-14 17:27:14.109110+0800 Basic_iOS[48718:1193247] read2: You Have 10 Orange !
2020-03-14 17:27:15.110935+0800 Basic_iOS[48718:1193247] write3: You Have 10 Peach !
2020-03-14 17:27:16.111248+0800 Basic_iOS[48718:1193248] write4: You Have 20 Grape !
2020-03-14 17:27:18.115692+0800 Basic_iOS[48718:1193247] read3: You Have 20 Grape !
2020-03-14 17:27:18.115692+0800 Basic_iOS[48718:1193248] read4: You Have 20 Grape !

*/

共同学习,欢迎指正...


参考文章:

//www.greatytc.com/p/a459ea2e7fec

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容

  • 一. NSConditionLock NSConditionLock是对NSCondition的进一步封装,可以设...
    Imkata阅读 775评论 0 0
  • 多线程基本概念 单核CPU,同一时间cpu只能处理1个线程,只有1个线程在执行 。多线程同时执行:是CPU快速的在...
    WeiHing阅读 705评论 1 5
  • ​ 前言:这可能是史上最全面的一篇iOS 多线程博客了(王婆卖瓜一番😄),从多线程的基本概念,进程的概念,引出i...
    阿饼six阅读 848评论 2 11
  • iOS中多线程 首先看一道面试题 iOS中多线程有哪些实现方案? iOS中,多线程一般有三种方案GCD、NSOpe...
    木子奕阅读 652评论 0 1
  • 一: 多线程的基本概念1.同步与异步的概念1.1 同步 必须等待当前语句执行完毕,才可以执行下一个语句。1.2...
    程序_猿阅读 3,392评论 1 16