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