OC 底层原理笔记

22 多线程之atomic,读写安全

2020-01-20  本文已影响0人  zysmoon
一 atomic

atomic用于保证属性setter、getter的原子性操作,相当于在gettersetter内部加了线程同步的锁

可以参考源码objc4的objc-accessors.mm

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);
}

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);
}

分析

nonatomicatomic

@property (copy, atomic) NSString *name;

- (void)setName:(NSString *)name {
    // 加锁
    _name = name;
    // 解锁
}

- (NSString *)name {
// 加锁
    return _name;
// 解锁
}

@property (strong, atomic) NSMutableArray *data;

Person *p = [[Person alloc] init];
p.data = [NSMutableArray array];

// 以下操作就不能保证线程安全了
for (int i = 0; i < 10; i++) {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [p.data addObject:@"1"];
    });
}

虽然data属性是声明为atomic,但是也只是在p.data(实际上调用了get方法)和p.data = [NSMutableArray array];(实际上调用了set方法)是安全的。但是多条线程同时添加对象时,即[p.data addObject:@"1"];并不能保证线程安全。

二 读与写的方案

思考如何实现以下场景

上面的场景就是典型的“多读单写”,经常用于文件等数据的读写操作,iOS中的实现方案有

2.1 pthread_rwlock

等待锁的线程会进入休眠

1653926-c5785b8c58338b76.png

代码例子如下

#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);
}

执行结果

1653926-f9753ce765525426.png
2.2 dispatch_barrier_async

重要方法

// 初始化队列
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];
});

原理如下

1653926-d9f78ddc974b7c29.png

代码例子如下

@property (strong, nonatomic) dispatch_queue_t queue;

// 栅栏
- (void)barrier_async_test {
    self.queue = dispatch_queue_create("rw_queue", DISPATCH_QUEUE_CONCURRENT);

    for (int i = 0; i < 5; i++) {
        dispatch_async(self.queue, ^{
            [self read];
        });

        dispatch_async(self.queue, ^{
            [self read];
        });

        dispatch_barrier_async(self.queue, ^{
            [self write];
        });
    }
}

- (void)read {
    sleep(1);
    NSLog(@"read");
}

- (void)write {
    sleep(1);
    NSLog(@"write");
}

执行结果如下

1653926-a7ccf12317e97a22.png

本文参考:
路飞_Luck (https://www.jianshu.com/p/07f7b96bb03f)
以及借鉴MJ的教程视频
非常感谢.


项目源码 - GCD-读写安全
项目源码 - GCD-automic

上一篇下一篇

猜你喜欢

热点阅读