您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多線程:NSThread 與 @synchronized 加鎖實作

編輯:iOS 開發綜合

當多個執行緒同時操作同一個變數時,就可能發生資料競爭。此時需要透過鎖機制保護共享資源。本文以多執行緒售票為例,說明如何使用 @synchronized 為 NSThread 加鎖。

一、為什麼需要加鎖

如果多個執行緒同時讀寫同一個變數,可能會出現票數錯亂、重複賣出或超出範圍等問題。加鎖可以確保同一時間只有一個執行緒進入關鍵區段。

二、建立多個執行緒

@property (strong, nonatomic) NSThread *thread1;
@property (strong, nonatomic) NSThread *thread2;
@property (strong, nonatomic) NSThread *thread3;
@property (assign, nonatomic) NSInteger leftTickets;

- (void)viewDidLoad {
    [super viewDidLoad];

    self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];

    self.thread1.name = @"thread1";
    self.thread2.name = @"thread2";
    self.thread3.name = @"thread3";

    self.leftTickets = 10;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.thread1 start];
    [self.thread2 start];
    [self.thread3 start];
}

三、使用 @synchronized 加鎖

- (void)sellTickets {
    while (1) {
        @synchronized (self) {
            if (self.leftTickets > 0) {
                [NSThread sleepForTimeInterval:0.2];

                self.leftTickets -= 1;
                NSLog(@"剩餘票數:%ld", (long)self.leftTickets);
                NSLog(@"當前執行緒:%@", [NSThread currentThread]);
            }
        }

        if (self.leftTickets == 0) {
            NSLog(@"票賣完了");
            NSLog(@"退出執行緒:%@", [NSThread currentThread]);
            [NSThread exit];
        }
    }
}

四、@synchronized 的作用

@synchronized 主要做兩件事:

  • 阻塞當前執行緒,直到鎖內程式碼執行完畢。
  • 在進入鎖之前,檢查是否有其他執行緒正在執行相同鎖標記的程式碼。

只有取得鎖的執行緒才能進入關鍵區段,其他執行緒會等待。

五、注意事項

不建议在 @synchronized 區塊內部直接退出執行緒。若某個執行緒在鎖內退出,其他等待的執行緒可能永遠無法取得鎖,造成不必要的資源浪費。

較好的做法是將退出判斷放在鎖外:

if (self.leftTickets == 0) {
    [NSThread exit];
}

這樣可以確保每個執行緒都能正常結束,避免鎖狀態卡住。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved