當多個執行緒同時操作同一個變數時,就可能發生資料競爭。此時需要透過鎖機制保護共享資源。本文以多執行緒售票為例,說明如何使用 @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];
}- (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 區塊內部直接退出執行緒。若某個執行緒在鎖內退出,其他等待的執行緒可能永遠無法取得鎖,造成不必要的資源浪費。
較好的做法是將退出判斷放在鎖外:
if (self.leftTickets == 0) {
[NSThread exit];
}這樣可以確保每個執行緒都能正常結束,避免鎖狀態卡住。