多線程的安全隱患


1. 資源共享
1塊資源可能會被多個線程共享,也就是多個線程可能會訪問同一塊資源;
比如多個線程訪問同一個對象、同一個變量、同一個文件;
當多個線程訪問同一塊資源時,很容易引發數據錯亂和數據安全問題。

2. 安全隱患示例存錢取錢


3. 安全隱患分析


4. 安全隱患解決互斥鎖


5. 互斥鎖使用格式

@synchronized(鎖對象) {// 需要鎖定的代碼 }

注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的。


6. 互斥鎖的優缺點
優點:能有效防止因多線程搶奪資源造成的數據安全問題。
缺點:需要消耗大量的CPU資源

7. 互斥鎖的使用前提:
多條線程搶奪同一塊資源。

8. 相關專業術語:線程同步
線程同步的意思是:多條線程按順序地執行任務。
互斥鎖,就是使用了線程同步技術。


9.互斥鎖的一個Demo


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self demo];

}

-(void)demo {

    //模擬2個賣票窗口

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];

    thread.name = @"買票窗口1";

    [thread start];

    

    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];

    thread2.name = @"買票窗口2";

    [thread2 start];

}

//賣票

-(void)sellTicket{

    while (YES) {

        //模擬網絡卡

        [NSThread sleepForTimeInterval:1];

     //互斥鎖運行步驟詳解:    

        //線程1 票數 讀取5 時間到 保存票數5

        //線程2 票數 讀取5 時間到 保存票數5

        //線程1 票數5 還原票數5 5-1=4 輸出4

        //線程2 票數4 還原票數5 5-1=4 輸出4

        

        //任意對象

// NSObject *obj = [[NSObject alloc] init];

        

        //加鎖的語法,括號內爲鎖的對象,每個對象內都有一把鎖,默認鎖是開着的

        //同步鎖

//[NSUserDefaults standardUserDefaults] synchronize 方便書寫synchronized

        @synchronized(self.obj){

            if(self.tickets >0){

                self.tickets = self.tickets - 1;

                NSLog(@"%@ 餘票 %d",[NSThread currentThread],self.tickets);

                continue;

            }

        }

        NSLog(@"沒有票啦");

        break;

    }

}






發佈了53 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章