官方文件的說法很直接:
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.
翻譯過來就是:在多執行緒環境下,通知在哪一條執行緒被 post,就在哪一條執行緒被轉發,而不一定是註冊觀察者時所處的那條執行緒。也就是說,發送與接收處理都發生在同一條執行緒上。
- (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");
}
輸出結果:
current thread = {number = 1, name = main}
current thread = {number = 2, name = (null)}
test notification
雖然觀察者是在主執行緒註冊的,但在全域佇列中 post 的通知,並不是在主執行緒被處理。因此,如果回調裡要做 UI 相關操作,必須自己確保切回主執行緒。
文件接著說:
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.
思路是:在通知抵達的預設執行緒上攔下它,再導引到目標執行緒。實作方式之一是自訂一個通知佇列(這裡指的是陣列,不是 NSNotificationQueue),用來暫存需要重定向的通知。註冊觀察者的方式不變,通知抵達時先檢查 post 它的執行緒是否為期望的執行緒;若不是,就把它放進佇列,並送出一個訊號告知目標執行緒有通知要處理。目標執行緒收到訊號後,把通知移出佇列並處理。
官方文件已提供範例,這裡借用並實測。核心結構需要四個成員:通知佇列、期望執行緒、用來保護佇列的鎖,以及一個用來送訊號的 Mach 連接埠。
@property (nonatomic) NSMutableArray *notifications; // 通知佇列
@property (nonatomic) NSThread *notificationThread; // 期望執行緒
@property (nonatomic) NSLock *notificationLock; // 避免執行緒衝突
@property (nonatomic) NSMachPort *notificationPort; // 向期望執行緒送訊號的通道
// 初始化時把連接埠加入執行緒的 run loop
self.notificationThread = [NSThread currentThread];
self.notificationPort = [[NSMachPort alloc] init];
self.notificationPort.delegate = self;
[[NSRunLoop currentRunLoop] addPort:self.notificationPort forMode:(__bridge NSString *)kCFRunLoopCommonModes];
// 收到 Mach 訊息後,把佇列中的通知逐一取出處理
- (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) {
[self.notificationLock lock];
[self.notifications addObject:notification];
[self.notificationLock unlock];
[self.notificationPort sendBeforeDate:[NSDate date] components:nil from:nil reserved:0];
} else {
NSLog(@"current thread = %@", [NSThread currentThread]);
NSLog(@"process notification");
}
}
實測輸出:
current thread = {number = 1, name = main}
current thread = {number = 1, name = main}
process notification
在全域 dispatch 佇列中拋出的通知,如願在主執行緒被接收了。關於這個做法的細節與限制,可參考官方文件 Delivering Notifications To Particular Threads。當然,更好的做法可能是自己 subclass 一個 NSNotificationCenter,或另外寫一個專門負責轉發的類別。
蘋果之所以採用「同一執行緒 post 與轉發」的策略,應該是出於執行緒安全的考量。Threading Programming Guide 明確指出 NSNotification、NSNotificationCenter 等類別是執行緒安全的,同一個實例可以在多條執行緒中共用而無需加鎖。也就是說,我們可以在任何執行緒新增/移除觀察者,也可以在任何執行緒 post 通知。
但這是否代表可以高枕無憂?把最前面的範例稍微改造一下:
@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)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
// 其他地方
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
這就是我們平常寫的樣板:註冊觀察者、定義回調、在物件釋放時移除觀察者,然後在程式的某處 post 通知。如果一切都在同一條執行緒發生,或者至少 dealloc 是在 post 通知的那條執行緒上執行(注意:通知的 post 與轉發是同步的),那都沒問題。但若 dealloc 與 post 不在同一條執行緒,麻煩就來了。
@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
@implementation Observer
- (void)handleNotification:(NSNotification *)notification
{
NSLog(@"handle notification begin");
sleep(1);
NSLog(@"handle notification end");
self.i = 10; // 這裡可能已經是屍體
}
@end
// ViewController
- (void)viewDidLoad {
[super viewDidLoad];
__autoreleasing Observer *observer = [[Observer alloc] init];
}
這段程式碼在主執行緒註冊觀察者,通知卻在背景執行緒 post,回調裡刻意讓執行緒睡 1 秒再設定屬性。輸出如下:
handle notification begin Observer dealloc handle notification end // 於 self.i = 10 處拋出 EXC_BAD_ACCESS
經典的記憶體錯誤,程式崩潰。從輸出就能看出發生什麼事:
這個例子是刻意為之,但實務上並非不可能遇到。NSNotificationCenter 是執行緒安全的,並不代表我們的使用方式就安全。
NSNotificationCenter 雖然是執行緒安全的,但別被這個事實誤導。一旦牽涉多執行緒,仍需處處留意,避免踩到上面那類問題。想進一步了解,可參考 Observers and Thread Safety。