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 <pthread.h>
@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]);
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一. NSConditionLock NSConditionLock是对NSCondition的进一步封装,可以设...
    Imkata阅读 940评论 0赞 0
  • 1、进程 1)进程是一个具有一定独立功能的程序关于某次数据集合的一次运行活动,它是操作系统分配资源的基本单...
    Crics阅读 592评论 0赞 0
  • 单次函数dispatch_once 单次函数一般用来创建单例或者是执行只需要执行一次的程序。 dispatch_o...
    xxxxxxxx_123阅读 427评论 0赞 0
  • 本文内容任务、队列的概念、创建方式任务 + 队列的6种组合的执行方式线程间如何通信dispatch_once、di...
    小秀秀耶阅读 1,121评论 0赞 9
  • 目录:iOS多线程(一)--pthread、NSThreadiOS多线程(二)--GCD详解iOS多线程(三)--...
    Claire_wu阅读 1,169评论 0赞 6

友情链接更多精彩内容