iOS GCD(六)線程加鎖

iOS GCD (一) 任務(wù)+隊(duì)列 基礎(chǔ)組合
iOS GCD (二 ) dispatch_group 隊(duì)列組
iOS GCD(三) dispatch_barrier_async 柵欄方法
iOS GCD (四) dispatch_semaphore 信號(hào)量
iOS GCD(五) 死鎖案例分析
iOS GCD(六)線程加鎖

推薦鏈接
https://bestswifter.com/ios-lock/

線程枷鎖分為九種方式 可以參考以上鏈接,我們只詳細(xì)的講解其中三種 semaphore, NSLock,@synchronized

需要對(duì)線程加鎖的原因很多 接下來我們只講其中一種情況:
當(dāng)多條線程同時(shí)編輯一個(gè)任務(wù)時(shí)所造成的數(shù)據(jù)錯(cuò)亂
舉例說明:兩個(gè)火車票銷售窗口 共同銷售車站總共的50張車票??创a你最明白。

錯(cuò)誤案例:

/**
 * 非線程安全:不使用 semaphore
 * 初始化火車票數(shù)量、賣票窗口(非線程安全)、并開始賣票
 */
- (void)initTicketStatusNotSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印當(dāng)前線程
    NSLog(@"semaphore---begin");
    
    self.ticketSurplusCount = 50;
    
    // queue1 代表北京火車票售賣窗口
    dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
    // queue2 代表上海火車票售賣窗口
    dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(queue1, ^{
        [weakSelf saleTicketNotSafe];
    });
    
    dispatch_async(queue2, ^{
        [weakSelf saleTicketNotSafe];
    });
}

/**
 * 售賣火車票(非線程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {
        
        if (self.ticketSurplusCount > 0) {  //如果還有票,繼續(xù)售賣
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票數(shù):%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已賣完,關(guān)閉售票窗口
            NSLog(@"所有火車票均已售完");
            break;
        }
        
    }
}

輸出結(jié)果(部分):
2018-02-23 22:25:35.789072+0800 YSC-GCD-demo[20712:5258914] currentThread---<NSThread: 0x604000068880>{number = 1, name = main}
2018-02-23 22:25:35.789260+0800 YSC-GCD-demo[20712:5258914] semaphore---begin
2018-02-23 22:25:35.789641+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):48 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
2018-02-23 22:25:35.789646+0800 YSC-GCD-demo[20712:5259175] 剩余票數(shù):49 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
2018-02-23 22:25:35.994113+0800 YSC-GCD-demo[20712:5259175] 剩余票數(shù):47 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
2018-02-23 22:25:35.994129+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):46 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
2018-02-23 22:25:36.198993+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):45 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}

可以看到在不考慮線程安全,不使用 semaphore 的情況下,得到票數(shù)是錯(cuò)亂的,這樣顯然不符合我們的需求,所以我們需要考慮線程安全問題。防止兩條線程同時(shí)對(duì)此任務(wù)進(jìn)行編輯,每次只能有一條線程執(zhí)行此任務(wù)。所以就用到了線程加鎖

加鎖方式一 dispatch_semaphore 自旋鎖

@interface ViewController (){
    NSInteger _ticketSurplusCount;
    dispatch_semaphore_t _semaphoreLock;
    NSLock *_lock;
  }
@end
/**
 * 線程安全:使用 semaphore 加鎖
 * 初始化火車票數(shù)量、賣票窗口(線程安全)、并開始賣票
 */
- (void)initTicketStatusSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印當(dāng)前線程
    NSLog(@"semaphore---begin");
    
    semaphoreLock = dispatch_semaphore_create(1);
    
    self.ticketSurplusCount = 50;
    
    // queue1 代表北京火車票售賣窗口
    dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
    // queue2 代表上?;疖嚻笔圪u窗口
    dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(queue1, ^{
        [weakSelf saleTicketSafe];
    });
    
    dispatch_async(queue2, ^{
        [weakSelf saleTicketSafe];
    });
}

/**
 * 售賣火車票(線程安全)
 */
- (void)saleTicketSafe {
    while (1) {
        // 相當(dāng)于加鎖
        dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
        
        if (self.ticketSurplusCount > 0) {  //如果還有票,繼續(xù)售賣
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票數(shù):%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已賣完,關(guān)閉售票窗口
            NSLog(@"所有火車票均已售完");
            
            // 相當(dāng)于解鎖
            dispatch_semaphore_signal(semaphoreLock);
            break;
        }
        
        // 相當(dāng)于解鎖
        dispatch_semaphore_signal(semaphoreLock);
    }
}

輸出結(jié)果為:
2018-02-23 22:32:19.814232+0800 YSC-GCD-demo[20862:5290531] currentThread---<NSThread: 0x6000000783c0>{number = 1, name = main}
2018-02-23 22:32:19.814412+0800 YSC-GCD-demo[20862:5290531] semaphore---begin
2018-02-23 22:32:19.814837+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):49 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:20.017745+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):48 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:20.222039+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):47 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
......
2018-02-23 22:32:29.024817+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):4 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:29.230110+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):3 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:29.433615+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):2 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:29.637572+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):1 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:29.840234+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):0 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:30.044960+0800 YSC-GCD-demo[20862:5290687] 所有火車票均已售完
2018-02-23 22:32:30.045260+0800 YSC-GCD-demo[20862:5290689] 所有火車票均已售完

加鎖方式二 @synchronized 互斥鎖

/**
 * 線程安全:使用 semaphore 加鎖
 * 初始化火車票數(shù)量、賣票窗口(線程安全)、并開始賣票
 */
- (void)initTicketStatusSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印當(dāng)前線程
    NSLog(@"semaphore---begin");
    
    _semaphoreLock = dispatch_semaphore_create(1);
    
    _ticketSurplusCount = 50;
    
    // queue1 代表北京火車票售賣窗口
    dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
    // queue2 代表上?;疖嚻笔圪u窗口
    dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(queue1, ^{
        [weakSelf saleTicketSafe];
    });
    
    dispatch_async(queue2, ^{
        [weakSelf saleTicketSafe];
    });
}

/**
 * 售賣火車票(線程安全)
 */
- (void)saleTicketSafe {
    while (1) {
        // 相當(dāng)于加鎖
        @synchronized(self) {
            if (self.ticketSurplusCount > 0) {  //如果還有票,繼續(xù)售賣
                self.ticketSurplusCount--;
                NSLog(@"%@", [NSString stringWithFormat:@"剩余票數(shù):%d 窗口:%@", _ticketSurplusCount, [NSThread currentThread]]);
                [NSThread sleepForTimeInterval:0.2];
            } else { //如果已賣完,關(guān)閉售票窗口
                NSLog(@"所有火車票均已售完");
                break;
            }
        }
    }
}

輸出結(jié)果為:
2018-04-27 14:58:49.255255+0700 GCD[86633:4440145] 剩余票數(shù):8 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.459695+0700 GCD[86633:4440148] 剩余票數(shù):6 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:49.459695+0700 GCD[86633:4440145] 剩余票數(shù):7 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.663997+0700 GCD[86633:4440145] 剩余票數(shù):5 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.664065+0700 GCD[86633:4440148] 剩余票數(shù):4 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:49.868848+0700 GCD[86633:4440145] 剩余票數(shù):3 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.869419+0700 GCD[86633:4440148] 剩余票數(shù):2 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:50.072308+0700 GCD[86633:4440145] 剩余票數(shù):1 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:50.072308+0700 GCD[86633:4440148] 剩余票數(shù):0 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:50.276839+0700 GCD[86633:4440148] 所有火車票均已售完
2018-04-27 14:58:50.276839+0700 GCD[86633:4440145] 所有火車票均已售完

加鎖方式三 NSLock

/**
 * 線程安全:使用 semaphore 加鎖
 * 初始化火車票數(shù)量、賣票窗口(線程安全)、并開始賣票
 */
- (void)initTicketStatusSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印當(dāng)前線程
    NSLog(@"semaphore---begin");
    
    _semaphoreLock = dispatch_semaphore_create(1);
    
    _ticketSurplusCount = 50;
    
    // queue1 代表北京火車票售賣窗口
    dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
    // queue2 代表上?;疖嚻笔圪u窗口
    dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(queue1, ^{
        [weakSelf saleTicketSafe];
    });
    
    dispatch_async(queue2, ^{
        [weakSelf saleTicketSafe];
    });
}

/**
 * 售賣火車票(線程安全)
 */
- (void)saleTicketSafe {
    while (1) {
        // 相當(dāng)于加鎖
         [_lock lock];
        if (self.ticketSurplusCount > 0) {  //如果還有票,繼續(xù)售賣
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票數(shù):%d 窗口:%@", _ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已賣完,關(guān)閉售票窗口
            NSLog(@"所有火車票均已售完");
            break;
        }
        [_lock unlock];
    }
}

輸出結(jié)果為:
2018-04-27 14:58:49.255255+0700 GCD[86633:4440145] 剩余票數(shù):8 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.459695+0700 GCD[86633:4440148] 剩余票數(shù):6 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:49.459695+0700 GCD[86633:4440145] 剩余票數(shù):7 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.663997+0700 GCD[86633:4440145] 剩余票數(shù):5 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.664065+0700 GCD[86633:4440148] 剩余票數(shù):4 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:49.868848+0700 GCD[86633:4440145] 剩余票數(shù):3 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:49.869419+0700 GCD[86633:4440148] 剩余票數(shù):2 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:50.072308+0700 GCD[86633:4440145] 剩余票數(shù):1 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
2018-04-27 14:58:50.072308+0700 GCD[86633:4440148] 剩余票數(shù):0 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
2018-04-27 14:58:50.276839+0700 GCD[86633:4440148] 所有火車票均已售完
2018-04-27 14:58:50.276839+0700 GCD[86633:4440145] 所有火車票均已售完

此處總結(jié)完畢,后續(xù)更精彩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 鎖是一種同步機(jī)制,用于多線程環(huán)境中對(duì)資源訪問的限制iOS中常見鎖的性能對(duì)比圖(摘自:ibireme): iOS鎖的...
    LiLS閱讀 1,627評(píng)論 0 6
  • Q:為什么出現(xiàn)多線程? A:為了實(shí)現(xiàn)同時(shí)干多件事的需求(并發(fā)),同時(shí)進(jìn)行著下載和頁面UI刷新。對(duì)于處理器,為每個(gè)線...
    幸福相依閱讀 1,721評(píng)論 0 2
  • 前言 iOS開發(fā)中由于各種第三方庫(kù)的高度封裝,對(duì)鎖的使用很少,剛好之前面試中被問到的關(guān)于并發(fā)編程鎖的問題,都是一知...
    喵渣渣閱讀 3,864評(píng)論 0 33
  • 《澳洲金融評(píng)論》報(bào)道,根據(jù)交易分析顯示,隨著投資者需求下滑且公寓價(jià)格下跌,開發(fā)商提供30,000澳元的傭金支付以及...
    繁榮世界閱讀 231評(píng)論 0 0
  • 童年在這里做了個(gè)夢(mèng),然后便有了長(zhǎng)長(zhǎng)的思念。----大連 大連本是我父親從軍的地方,年幼的我曾在那里度過了大半年的時(shí)...
    二月二zzf閱讀 626評(píng)論 8 6

友情鏈接更多精彩內(nèi)容