NSNotification 也有”消息转发“,会不会崩溃呢?

版权声明:原创文章,未经博主允许禁止转载。欢迎点击头像上方“郭晓东的专栏”查看专栏 https://blog.csdn.net/hherima/article/details/82835433

NSNotification与多线程

官方文档: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,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。

比如:我们在全局队列中发一个 NSNotification,主线程注册这个Notification。那么接收到这个通知也是在全局队列的线程。

#import <UIKit/UIKit.h>

@interface ThreadViewController : UIViewController

@end
#import "ThreadViewController.h"
#define TEST_NOTIFICATION  @"TEST_NOTIFICATION"
@interface ThreadViewController ()

@end




@implementation ThreadViewController
- (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");
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

输出结果如下,注册是main thread,接收到不是main thread

2018-09-25 10:29:27.583398+0800 onlineLayout[1219:28861] register in thread = <NSThread: 0x604000077040>{number = 1, name = main}
2018-09-25 10:29:27.583621+0800 onlineLayout[1219:28886] handleNotification in thread = <NSThread: 0x60000007ba40>{number = 3, name = (null)}

这时,就有一个问题了,如果我们的Notification是在二级线程中post的,如何能在主线程中对这个Notification进行处理呢?或者换个提法,如果我们希望一个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这个Notification的线程是不是我们所期望的线程,如果不是,则将这个Notification存储到我们的队列中,并发送一个信号(signal)到期望的线程中,来告诉这个线程需要处理一个Notification。指定的线程在收到信号后,将Notification从队列中移除,并进行处理。

官方文档已经给出了示例代码,在此借用一下,以测试实际结果:

在不同线程中post和转发一个Notification

#import <UIKit/UIKit.h>

@interface NotifiViewController : UIViewController<NSMachPortDelegate>
@property (nonatomic) NSMutableArray *notifications;   // 通知队列
@property (nonatomic) NSThread    *notificationThread; // 期望线程
@property (nonatomic) NSLock   *notificationLock;// 用于对通知队列加锁的锁对象,避免线程冲突
@property (nonatomic) NSMachPort  *notificationPort;   // 用于向期望线程发送信号的通信端口
@end
#import "NotifiViewController.h"

@interface NotifiViewController ()

@end
#define TEST_NOTIFICATION  @"TEST_NOTIFICATION"

@implementation NotifiViewController
- (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: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)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

输出:

2018-09-25 10:35:00.088912+0800 onlineLayout[1331:34495] regester in thread = <NSThread: 0x600000068480>{number = 1, name = main}
2018-09-25 10:35:00.106164+0800 onlineLayout[1331:34495] processNotification in thread = <NSThread: 0x600000068480>{number = 1, name = main}
2018-09-25 10:35:00.106281+0800 onlineLayout[1331:34495] 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在线程安全性方面已经做了不少工作了,那是否意味着我们可以高枕无忧了呢?基本可以高枕无忧了,(这个跟南峰子的描述有所出入,毕竟这是2018年了iOS SDK已经进化了),举例:

三个类viewController,Observer,poster。poster在后台线程发了一个Notification调用handleNotification方法,但是Observer对象并没有在handleNotification过程中释放。而是等待handleNotification执行完成再释放。完整代码如下:

#import <UIKit/UIKit.h>

@interface CrashController : UIViewController

@end
#import "CrashController.h"
#define TEST_NOTIFICATION  @"TEST_NOTIFICATION"

@interface Poster : NSObject{
 NSThread *_testThread;
}
@end
#include<pthread.h>
@implementation Poster

- (instancetype)init
{
    self = [super init];
    
    if (self){
        //开启线程模式1:持有self对象
        [self performSelectorInBackground:@selector(postNotification) withObject:nil];
        
        
        //开启线程模式2:持有self对象
//        _testThread = [[NSThread alloc] initWithTarget:self
//                                              selector:@selector(postNotification)
//                                                object:nil];
//        [_testThread start];
        
        //开启线程模式3:不持有self, 创建pthread线程
        //pthread_t thread;
        //pthread_create(&thread, NULL, createChildThread, NULL);
        
    }
    
    return self;
}
/*
这里也可以调用[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
但是postNotificationName这个方法会持有注册者(即Observer),Observer还是不会释放。
*/
void * createChildThread(void * param) {
    // 在子线程中来一个耗时操作
    for (int i = 0; i < 100; i++) {
        if(i==5){
            //巧妙的在Observer dealloc之前进入handleNotification:函数,想等待Observer 执行dealloc,但是结果还是一样的,Observer的handleNotification:方法执行过程中。NSNotificationCenter会强持有注册者一段时间,执行完再释放
            [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
        }
        NSLog(@"%zd:%@", i, [NSThread currentThread]);
        
    }
    return NULL;
}

/*
 但notificationcenter的post方法会持有对象。
 */
- (void)postNotification{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
    sleep(2);
    NSLog(@"Poster postNotification over");
}

@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(5);
        NSLog(@"handle notification end");
    
    self.i = 10;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    NSLog(@"Observer dealloc");
}

@end


@implementation CrashController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    __autoreleasing Observer *observer = [[Observer alloc] init];

//    for (int i = 0; i < 1000; i++) {
//        NSLog(@"%zd:%@", i, [NSThread currentThread]);
//    }
}
//方案1 的打印
2018-09-26 22:47:39.297436+0800 onlineLayout[1915:49413] handle notification begin
2018-09-26 22:47:44.364518+0800 onlineLayout[1915:49413] handle notification end
2018-09-26 22:47:44.365574+0800 onlineLayout[1915:49413] Observer dealloc
2018-09-26 22:47:46.439614+0800 onlineLayout[1915:49413] Poster postNotification over

//方案2 NSTread方案
2018-09-27 11:14:46.699438+0800 onlineLayout[3588:105340] handle notification begin
2018-09-27 11:14:51.703349+0800 onlineLayout[3588:105340] handle notification end
2018-09-27 11:14:51.703808+0800 onlineLayout[3588:105340] Observer dealloc
2018-09-27 11:14:53.705585+0800 onlineLayout[3588:105340] Poster postNotification over

//方案3 pthread的打印
2018-09-27 11:13:31.928115+0800 onlineLayout[3553:103469] 0:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:31.928342+0800 onlineLayout[3553:103469] 1:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:31.928503+0800 onlineLayout[3553:103469] 2:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:31.928621+0800 onlineLayout[3553:103469] 3:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:31.928736+0800 onlineLayout[3553:103469] 4:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:31.928815+0800 onlineLayout[3553:103469] handle notification begin
2018-09-27 11:13:36.933843+0800 onlineLayout[3553:103469] handle notification end
2018-09-27 11:13:36.934280+0800 onlineLayout[3553:103469] Observer dealloc
2018-09-27 11:13:36.934630+0800 onlineLayout[3553:103469] 5:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:36.934863+0800 onlineLayout[3553:103469] 6:<NSThread: 0x600000079e80>{number = 3, name = (null)}
2018-09-27 11:13:36.935104+0800 onlineLayout[3553:103469] 7:<NSThread: 0x600000079e80>{number = 3, name = (null)}

很完美,只有当handleNotification处理完成,Observer才dealloc

猜你喜欢

转载自blog.csdn.net/hherima/article/details/82835433
今日推荐