標籤:
先來看一下代碼:
- (void)viewDidLoad { [super viewDidLoad]; self.testStr = @"String initial complete"; [self performSelector:@selector(changeStr) withObject:nil afterDelay:0.5]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSLog(@"before sleep %@",self.testStr); sleep(3); NSLog(@"after sleep %@",self.testStr); });}- (void)changeStr{ self.testStr = @"String has changed";}
執行結果:
2016-10-14 09:11:40.525 安全執行緒測試[49097:11809626] before sleep String initial complete2016-10-14 09:11:43.598 安全執行緒測試[49097:11809626] after sleep String has changed
會發現在非同步執行中如果testStr改變了,那麼非同步線程裡的testStr也會改變這樣就沒法保證非同步對資源獨佔操作
如果在非同步block裡建立一個str賦值如下代碼:
- (void)viewDidLoad { [super viewDidLoad]; self.testStr = @"String initial complete"; [self performSelector:@selector(changeStr) withObject:nil afterDelay:0.5]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSString *str = self.testStr; NSLog(@"before sleep %@",str); sleep(3); NSLog(@"after sleep %@",str); });}- (void)changeStr{ self.testStr = @"String has changed";}
執行結果:
2016-10-14 09:15:09.785 安全執行緒測試[49319:11822894] before sleep String initial complete2016-10-14 09:15:12.786 安全執行緒測試[49319:11822894] after sleep String initial complete
這樣新的string就不會受到外部改變的影響,但是如果在這個賦值時刻self.asStr已變成野指標那麼後面的操作還是會出錯,雖然這樣情況不是那麼容易出現。
如何防止這種情況呢,可以看看下面的代碼:
- (void)viewDidLoad { [super viewDidLoad]; self.testStr = @"String initial complete"; [self performSelector:@selector(changeStr) withObject:nil afterDelay:0.5]; __weak __typeof(self.testStr) weakString = self.testStr; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ __strong __typeof(weakString) strongString = weakString; if(strongString) { NSLog(@"before sleep %@",strongString); sleep(3); NSLog(@"after sleep %@",strongString); } });}- (void)changeStr{ self.testStr = @"String has changed";}
執行結果:
2016-10-14 09:18:40.320 安全執行緒測試[49541:11835480] before sleep String initial complete2016-10-14 09:18:43.388 安全執行緒測試[49541:11835480] after sleep String initial complete
weakString會在self.asStr釋放時置為nil,如果不是nil時,能夠確保對象在block調用的完整周期裡面被retain,如果被搶佔對strongString的執行會繼續並且會產生一樣的值,如果strongString執行到時是nil,那麼block不能正確執行前已經返回,這樣就不會出現先前那樣的問題。
還可以用鎖來保證多個線程對一份資源在操作時不會被更改
#import "ViewController.h"#include <pthread.h>@interface ViewController (){ pthread_mutex_t _mutex;}@property (nonatomic, copy)NSString *testStr;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; pthread_mutex_init(&_mutex, NULL); self.testStr = @"String initial complete"; [self performSelector:@selector(changeStr) withObject:nil afterDelay:0.5]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ pthread_mutex_lock(&_mutex); NSLog(@"before sleep %@",self.testStr); sleep(3); NSLog(@"after sleep %@",self.testStr); pthread_mutex_unlock(&_mutex); });}- (void)changeStr{ pthread_mutex_lock(&_mutex); self.testStr = @"string has changed"; pthread_mutex_unlock(&_mutex);}- (void)dealloc{ pthread_mutex_destroy(&_mutex);}@end
執行結果:
2016-10-14 09:22:57.194 安全執行緒測試[49824:11850779] before sleep String initial complete2016-10-14 09:23:00.269 安全執行緒測試[49824:11850779] after sleep String initial complete
在RAC中使用的是OSSpinLock來保證安全執行緒的,不過幾位蘋果工程師在swift-dev郵件清單中討論weak屬性的安全執行緒問題的郵件裡爆出自旋鎖有bug,郵件地址:https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html。大概就是不同優先順序線程調度演算法會有優先順序反轉問題,比如低優先順序獲鎖訪問資源,高優先順序嘗試訪問時會等待,這時低優先順序又沒法爭過高優先順序導致任務無法完成lock釋放不了。也可以看看ReactiveCo社區的討論https://github.com/ReactiveCocoa/ReactiveCocoa/issues/2619
本來OSSpinLock是效能最高的鎖,但是由於如果不在同一個優先順序線程進行鎖操作就不能保證安全,那麼dispatch_semaphore和pthread_mutex這種僅次於自旋鎖的可以作為替代方案。我注意到facebook的KVOController在2016年5月17日時的一個Commit裡將所有OSSpinLock替換成了pthread_mutex,可參看這個commithttps://github.com/facebook/KVOController/commit/4f5c329b26f48b151eed82da085288763e2e1761。pthread_mutex會在新系統中效能得到很大的提升,所以可以考慮這個方案。
iOS開發安全執行緒問題