iOS開發系列-線程同步技術

來源:互聯網
上載者:User

標籤:.com   方案   get   air   操作   案例   常見   sre   協同   

概述

多線程的本質就是CPU輪流隨機分配給每條線程時間片資源執行任務,看起來多條線程同時執行任務。

多條線程同時訪問同一塊資源,比如操作同一個對象、統一變數、同一個檔案,就會引發資料錯亂和資料安全的問題。

多線程引發問題執行個體

這裡我也藉助網上兩個比較經典的案例,賣票和存取錢。

賣票案例

多個線程同時賣票,同一時間多個線層同時訪問票的總數,就會引發資料錯亂。

執行個體代碼

@interface ViewController ()@property (nonatomic, assign) int tickets;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.tickets = 30;    [self saleTicketTest];}- (void)saleTicketWithName:(NSString *)name{   int currTicketCount = self.tickets;    sleep(.2);    currTicketCount--;    self.tickets = currTicketCount;    NSLog(@"當前%@賣了一張,票還剩:%d張", name ,self.tickets);}- (void)saleTicketTest{    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);    dispatch_async(queue, ^{        for (int i=0; i<10; i++) {            [self saleTicketWithName:@"A"];        }    });        dispatch_async(queue, ^{        for (int i=0; i<10; i++) {            [self saleTicketWithName:@"B"];        }    });        dispatch_async(queue, ^{        for (int i=0; i<10; i++) {            [self saleTicketWithName:@"C"];        }    });}@end

異常結果:

存錢取錢案例

執行個體代碼

#import "ViewController.h"@interface ViewController ()@property (nonatomic, assign) int currMoney;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        self.currMoney = 1000;    [self moneyTest];}- (void)moneyTest{        dispatch_async(dispatch_get_global_queue(0, 0), ^{        for (int i=0; i<4; i++) {            [self saveMoney];        }    });    dispatch_async(dispatch_get_global_queue(0, 0), ^{        for (int i=0; i<4; i++) {            [self drawMoney];        }    });}// 存錢- (void)saveMoney{    int money = self.currMoney;    sleep(.3);    money += 100;    self.currMoney = money;    NSLog(@"存了100,還剩%d元", self.currMoney);    }// 取錢- (void)drawMoney{    int money = self.currMoney;    sleep(.3);    money -= 50;    self.currMoney = money;    NSLog(@"取了50,還剩%d元", self.currMoney);}

異常結果:

多安全執行緒隱患的解決方案

開發中解決多安全執行緒隱患的方案-使用線程同步技術。同步(協同步調,按預定的先後順序執行)
常見的線程同步技術就是加鎖。

iOS中線程同步的方案根據效能優先順序排序:

線程同步的方案 需要匯入標頭檔 類別 注意事項
os_unfair_lock <os/lock.h> 互斥鎖 iOS10才開始提供,用來替代OSSpinLock
OSSpinLock <libkern/OSAtomic.h> 自旋鎖 目前不在安全,可能會出現優先順序反轉問題
dispatch_semaphore
pthread_mutex
dispatch_queue(DISPATCH_SENTINEL)
NSLock
oNSCondition <os/lock.h>
pthread_mutex(recuresive)
NSRecursiveLock
NSConditionLock
@synchronized

iOS開發系列-線程同步技術

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.