iOS-多線程-讀寫安全

用dispatch_barrier_sync實現(xiàn)多讀單寫,用dispatch_semaphore實現(xiàn)單讀單寫

// 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,用柵欄函數(shù)實現(xiàn)線程安全
    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 的實現(xiàn)(無法多讀)
// 通過宏定義對代碼塊進行加鎖操作
#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]);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 一. NSConditionLock NSConditionLock是對NSCondition的進一步封裝,可以設...
    Imkata閱讀 802評論 0 0
  • 1、進程 1)進程是一個具有一定獨立功能的程序關于某次數(shù)據(jù)集合的一次運行活動,它是操作系統(tǒng)分配資源的基本單...
    Crics閱讀 493評論 0 0
  • 單次函數(shù)dispatch_once 單次函數(shù)一般用來創(chuàng)建單例或者是執(zhí)行只需要執(zhí)行一次的程序。 dispatch_o...
    xxxxxxxx_123閱讀 377評論 0 0
  • 本文內(nèi)容任務、隊列的概念、創(chuàng)建方式任務 + 隊列的6種組合的執(zhí)行方式線程間如何通信dispatch_once、di...
    小秀秀耶閱讀 1,041評論 0 9
  • 目錄:iOS多線程(一)--pthread、NSThreadiOS多線程(二)--GCD詳解iOS多線程(三)--...
    Claire_wu閱讀 1,096評論 0 6