iOS-多线程-读写安全

用dispatch_barrier_sync实现多读单写,用dispatch_semaphore实现单读单写

// dispatch_barrier_async-多读单写
self.queue = dispatch_queue_create("re_queue", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10; i++) {
        [self read];
        [self write];
    }
- (void)read{
    dispatch_async(self.queue, ^{
        sleep(1);
        NSLog(@"%s",__func__);
    });
}

- (void)write{
    dispatch_barrier_async(self.queue, ^{
        sleep(1);
        NSLog(@"%s",__func__);
    });
 }


-(NSUInteger)ticketCount {
    __block NSUInteger count;
    //因为要立即返回,所以我们用dispatch_sync
    dispatch_sync(_concurrent_queue, ^{
        count = self->_ticketCount;
    });
    return count;
}
- (void)setTicketCount:(NSUInteger)ticketCount {
    //对于写操作,我们这里用dispatch_barrier_async,用栅栏函数实现线程安全
    dispatch_barrier_async(_concurrent_queue, ^{
        if (ticketCount != self->_ticketCount) {
            self->_ticketCount = ticketCount;
        }
    });
}
// pthread_rwlock
#import 
@property (nonatomic,assign) pthread_rwlock_t lock;
pthread_rwlock_init(&_lock, NULL);
   dispatch_queue_t queue =  dispatch_queue_create(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);
}
// YYKit 中 YYThreadSafeArray 的实现(无法多读)
// 通过宏定义对代码块进行加锁操作
#define LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \
__VA_ARGS__; \
dispatch_semaphore_signal(_lock);

// id obj = array[idx];
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
    LOCK(id o = [_arr objectAtIndexedSubscript:idx]); return o;
}
// array[idx] = obj;
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx {
    LOCK([_arr setObject:obj atIndexedSubscript:idx]);
}

你可能感兴趣的:(iOS-多线程-读写安全)