前陣子和同事聊到 Notification 在多執行緒下的轉發問題,索性整理成文,記錄下來。
先翻翻官方文件,它是這麼說的:
In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.
翻譯過來就是:
在多執行緒應用中,Notification 在哪個執行緒被 post,就在哪個執行緒被轉發,而不一定是註冊觀察者的那個執行緒。
換句話說,Notification 的發送與接收處理,都發生在同一個執行緒裡。為了說明這一點,我們先看個範例:
程式碼清單 1:Notification 的發送與處理
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"current thread = %@", [NSThread currentThread]); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil]; }); } - (void)handleNotification:(NSNotification *)notification { NSLog(@"current thread = %@", [NSThread currentThread]); NSLog(@"test notification"); } @end它的輸出如下:
2015-03-11 22:05:12.856 test[865:45102] current thread = {number = 1, name = main} 2015-03-11 22:05:12.857 test[865:45174] current thread = {number = 2, name = (null)} 2015-03-11 22:05:12.857 test[865:45174] test notification可以看到,雖然我們在主執行緒註冊了通知的觀察者,但在全域佇列中 post 出來的 Notification,並不是在主執行緒處理的。所以這時就得當心:如果我們想在回呼裡處理與 UI 相關的操作,必須確保它是在主執行緒中執行。
於是問題來了:如果 Notification 是在二級執行緒中 post 的,我們要如何讓它在主執行緒中被處理?換個說法,如果我們希望一個 Notification 的 post 執行緒與轉發執行緒不是同一個,該怎麼辦?我們看看官方文件怎麼說:
For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
這裡講到了「重定向」——在 Notification 所在的預設執行緒中捕獲這些分發的通知,再把它們重定向到指定的執行緒。
一種重定向的實作思路,是自訂一個通知佇列(注意,這裡指的是一個陣列,而非 NSNotificationQueue 物件),讓它維護那些需要重定向的 Notification。我們仍像平常一樣註冊觀察者,當 Notification 送達時,先檢查 post 它的執行緒是否是我們期望的那個;若不是,就把它存進我們的佇列,並送出一個信號(signal)給期望的執行緒,告訴它有待處理的 Notification。指定執行緒收到信號後,再從佇列中取出 Notification 並處理。
官方文件已經給出了範例程式碼,我借來一用,實際驗證一下結果:
程式碼清單 2:在不同執行緒中 post 和轉發一個 Notification
@interface ViewController () @property (nonatomic) NSMutableArray *notifications; // 通知隊列 @property (nonatomic) NSThread *notificationThread; // 期望線程 @property (nonatomic) NSLock *notificationLock; // 用於對通知隊列加鎖的鎖對象,避免線程沖突 @property (nonatomic) NSMachPort *notificationPort; // 用於向期望線程發送信號的通信端口 @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"current thread = %@", [NSThread currentThread]); // 初始化 self.notifications = [[NSMutableArray alloc] init]; self.notificationLock = [[NSLock alloc] init]; self.notificationThread = [NSThread currentThread]; self.notificationPort = [[NSMachPort alloc] init]; self.notificationPort.delegate = self; // 往當前線程的run loop添加端口源 // 當Mach消息到達而接收線程的run loop沒有運行時,則內核會保存這條消息,直到下一次進入run loop [[NSRunLoop currentRunLoop] addPort:self.notificationPort forMode:(__bridge NSString *)kCFRunLoopCommonModes]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"TestNotification" object:nil]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil]; }); } - (void)handleMachMessage:(void *)msg { [self.notificationLock lock]; while ([self.notifications count]) { NSNotification *notification = [self.notifications objectAtIndex:0]; [self.notifications removeObjectAtIndex:0]; [self.notificationLock unlock]; [self processNotification:notification]; [self.notificationLock lock]; }; [self.notificationLock unlock]; } - (void)processNotification:(NSNotification *)notification { if ([NSThread currentThread] != _notificationThread) { // Forward the notification to the correct thread. [self.notificationLock lock]; [self.notifications addObject:notification]; [self.notificationLock unlock]; [self.notificationPort sendBeforeDate:[NSDate date] components:nil from:nil reserved:0]; } else { // Process the notification here; NSLog(@"current thread = %@", [NSThread currentThread]); NSLog(@"process notification"); } } @end運行後,輸出如下:
2015-03-11 23:38:31.637 test[1474:92483] current thread = {number = 1, name = main} 2015-03-11 23:38:31.663 test[1474:92483] current thread = {number = 1, name = main} 2015-03-11 23:38:31.663 test[1474:92483] process notification可以看到,我們在全域 dispatch 佇列中拋出的 Notification,如願地在主執行緒裡被接收到了。
這種實作的細節與侷限性,大家可以參考官方文件 Delivering Notifications To Particular Threads,這裡不再贅述。當然,更好的做法,或許是我們自己去子類化一個 NSNotificationCenter,或者另外寫一個類專門處理這種轉發。
NSNotificationCenter 的執行緒安全性
蘋果之所以採取「通知中心在同一個執行緒中 post 與轉發同一訊息」這一策略,應該是出於執行緒安全的考量。官方文件告訴我們,NSNotificationCenter 是一個執行緒安全類,我們可以在多執行緒環境下共用同一個 NSNotificationCenter 物件,而無需自行加鎖。原文在 Threading Programming Guide 中,是這麼寫的:
The following classes and functions are generally considered to be thread-safe. You can use the same instance from multiple threads without first acquiring a lock. NSArray ... NSNotification NSNotificationCenter ...
我們可以在任何執行緒中新增/移除通知的觀察者,也可以在任何執行緒中 post 一個通知。
NSNotificationCenter 在執行緒安全上已經做了不少功課,那是否意味著我們就能高枕無憂了?再回頭看看第一個例子,我們稍作改造,一步步來:
程式碼清單 3:NSNotificationCenter 的通用模式
@interface Observer : NSObject @end @implementation Observer - (instancetype)init { self = [super init]; if (self) { _poster = [[Poster alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil] } return self; } - (void)handleNotification:(NSNotification *)notification { NSLog(@"handle notification "); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } @end // 其它地方 [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];上面的程式碼,就是我們平常做的事:加一個通知監聽者,定義一個回呼,並在所屬物件釋放時移除監聽者;然後在程式的某處 post 一個通知。簡單明瞭。如果這一切都發生在同一個執行緒裡,或者至少 dealloc 方法是在 -postNotificationName: 的執行緒中運行(注意:NSNotification 的 post 與轉發是同步的),那麼一切正常,沒有執行緒安全問題。但如果 dealloc 方法與 -postNotificationName: 不在同一個執行緒中運行,會出什麼問題呢?
我們再改造一下上面的程式碼:
程式碼清單 4:NSNotificationCenter 引發的執行緒安全問題
#pragma mark - Poster @interface Poster : NSObject @end @implementation Poster - (instancetype)init { self = [super init]; if (self) { [self performSelectorInBackground:@selector(postNotification) withObject:nil]; } return self; } - (void)postNotification { [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil]; } @end #pragma mark - Observer @interface Observer : NSObject { Poster *_poster; } @property (nonatomic, assign) NSInteger i; @end @implementation Observer - (instancetype)init { self = [super init]; if (self) { _poster = [[Poster alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil]; } return self; } - (void)handleNotification:(NSNotification *)notification { NSLog(@"handle notification begin"); sleep(1); NSLog(@"handle notification end"); self.i = 10; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; NSLog(@"Observer dealloc"); } @end #pragma mark - ViewController @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; __autoreleasing Observer *observer = [[Observer alloc] init]; } @end這段程式碼在主執行緒加入了一個 TEST_NOTIFICATION 通知的監聽者,也在主執行緒中將它移除,而我們的 NSNotification 卻是在後台執行緒中 post 的。在通知處理函數裡,我們故意讓回呼所在的執行緒睡 1 秒鐘,然後才去設定屬性 i 的值。這時會發生什麼?先看看輸出:
2015-03-14 00:31:41.286 SKTest[932:88791] handle notification begin 2015-03-14 00:31:41.291 SKTest[932:88713] Observer dealloc 2015-03-14 00:31:42.361 SKTest[932:88791] handle notification end (lldb) // 程序在self.i = 10處拋出了"Thread 6: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)"
典型的記憶體錯誤,程式崩潰了。其實從輸出裡,我們就能看出到底發生了什麼。簡要梳理一下:
當我們註冊一個觀察者時,通知中心會持有觀察者的一個弱參照,以確保觀察者仍可用。
主執行緒呼叫 dealloc,會讓 Observer 物件的參照計數歸零,於是物件被釋放。
後台執行緒送出一個通知,若此時 Observer 尚未被釋放,通知中心便會轉發訊息並執行回呼;而一旦回呼執行途中物件被釋放,就會出現上面的問題。
當然,這個例子是刻意為之,但在實際編碼中,並不能完全排除遇到類似問題的可能。NSNotificationCenter 固然是執行緒安全的,但這並不意味著我們使用它就一定能保證執行緒安全,稍不留神,仍會栽在執行緒問題上。
那我們該怎麼辦?這裡有幾條不錯的建議:
盡量在同一個執行緒中處理通知相關的操作,大多數情況下,這樣都能確保通知正常運作。只是,我們無從確定 dealloc 究竟會在哪個執行緒被呼叫,所以這一點執行起來頗有難度。
註冊監聽時,使用基於 block 的 API。這樣,如果我們在 block 裡還要繼續存取 self 的屬性或方法,就能透過 weak-strong 的方式來處理。具體效果,大家不妨改改上面的程式碼試試。
使用具備安全生命週期的物件,這一點對單例物件來說再合適不過——它們在整個應用的生命週期內都不會被釋放。
使用代理。
小結
NSNotificationCenter 雖然是執行緒安全的,但別被這個事實迷惑。一旦牽涉多執行緒,我們還是要多留個心眼,避免踩進上面的執行緒陷阱。若想進一步了解,可以查閱 Observers and Thread Safety。
參考
Notification Programming Topics
Threading Programming Guide
NSNotification 的幾點說明
NSNotificationCenter is thread-safe NOT
Observers and Thread Safety