html5中文学习网

您的位置: 首页 > ios » 正文

IOS开发:Notification与多线程_IOS开发

[ ] 已经帮助:人解决问题

   先来看看官方的文档,是这样写的:FALHTML5中文学习网 - HTML5先行者学习网

  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.FALHTML5中文学习网 - HTML5先行者学习网

  翻译过来是:FALHTML5中文学习网 - HTML5先行者学习网

  在多线程应用中,Notification在哪个线程中post,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。FALHTML5中文学习网 - HTML5先行者学习网

  也就是说,Notification的发送与接收处理都是在同一个线程中。为了说明这一点,我们先来看一个示例:FALHTML5中文学习网 - HTML5先行者学习网

  代码清单1:Notification的发送与处理FALHTML5中文学习网 - HTML5先行者学习网

  @implementation ViewControllerFALHTML5中文学习网 - HTML5先行者学习网

  - (void)viewDidLoad {FALHTML5中文学习网 - HTML5先行者学习网

  [super viewDidLoad];FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"current thread = %@", [NSThread currentThread]);FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];FALHTML5中文学习网 - HTML5先行者学习网

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];FALHTML5中文学习网 - HTML5先行者学习网

  });FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)handleNotification:(NSNotification *)notificationFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"current thread = %@", [NSThread currentThread]);FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"test notification");FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  其输出结果如下:FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 22:05:12.856 test[865:45102] current thread = {number = 1, name = main}FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 22:05:12.857 test[865:45174] current thread = {number = 2, name = (null)}FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 22:05:12.857 test[865:45174] test notificationFALHTML5中文学习网 - HTML5先行者学习网

  可以看到,虽然我们在主线程中注册了通知的观察者,但在全局队列中post的Notification,并不是在主线程处理的。所以,这时候就需要注意,如果我们想在回调中处理与UI相关的操作,需要确保是在主线程中执行回调。FALHTML5中文学习网 - HTML5先行者学习网

  这时,就有一个问题了,如果我们的Notification是在二级线程中post的,如何能在主线程中对这个Notification进行处理呢?或者换个提法,如果我们希望一个Notification的post线程与转发线程不是同一个线程,应该怎么办呢?我们看看官方文档是怎么说的:FALHTML5中文学习网 - HTML5先行者学习网

  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.FALHTML5中文学习网 - HTML5先行者学习网

  这里讲到了“重定向”,就是我们在Notification所在的默认线程中捕获这些分发的通知,然后将其重定向到指定的线程中。FALHTML5中文学习网 - HTML5先行者学习网

  一种重定向的实现思路是自定义一个通知队列(注意,不是NSNotificationQueue对象,而是一个数组),让这个队列去维护那些我们需要重定向的Notification。我们仍然是像平常一样去注册一个通知的观察者,当Notification来了时,先看看post这个Notification的线程是不是我们所期望的线程,如果不是,则将这个Notification存储到我们的队列中,并发送一个信号(signal)到期望的线程中,来告诉这个线程需要处理一个Notification。指定的线程在收到信号后,将Notification从队列中移除,并进行处理。FALHTML5中文学习网 - HTML5先行者学习网

  官方文档已经给出了示例代码,在此借用一下,以测试实际结果:FALHTML5中文学习网 - HTML5先行者学习网

  代码清单2:在不同线程中post和转发一个NotificationFALHTML5中文学习网 - HTML5先行者学习网

  @interface ViewController ()FALHTML5中文学习网 - HTML5先行者学习网

  @property (nonatomic) NSMutableArray *notifications; // 通知队列FALHTML5中文学习网 - HTML5先行者学习网

  @property (nonatomic) NSThread *notificationThread; // 期望线程FALHTML5中文学习网 - HTML5先行者学习网

  @property (nonatomic) NSLock *notificationLock; // 用于对通知队列加锁的锁对象,避免线程冲突FALHTML5中文学习网 - HTML5先行者学习网

  @property (nonatomic) NSMachPort *notificationPort; // 用于向期望线程发送信号的通信端口FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  @implementation ViewControllerFALHTML5中文学习网 - HTML5先行者学习网

  - (void)viewDidLoad {FALHTML5中文学习网 - HTML5先行者学习网

  [super viewDidLoad];FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"current thread = %@", [NSThread currentThread]);FALHTML5中文学习网 - HTML5先行者学习网

  // 初始化FALHTML5中文学习网 - HTML5先行者学习网

  self.notifications = [[NSMutableArray alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  self.notificationLock = [[NSLock alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  self.notificationThread = [NSThread currentThread];FALHTML5中文学习网 - HTML5先行者学习网

  self.notificationPort = [[NSMachPort alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  self.notificationPort.delegate = self;FALHTML5中文学习网 - HTML5先行者学习网

  // 往当前线程的run loop添加端口源FALHTML5中文学习网 - HTML5先行者学习网

  // 当Mach消息到达而接收线程的run loop没有运行时,则内核会保存这条消息,直到下一次进入run loopFALHTML5中文学习网 - HTML5先行者学习网

  [[NSRunLoop currentRunLoop] addPort:self.notificationPortFALHTML5中文学习网 - HTML5先行者学习网

  forMode:(__bridge NSString *)kCFRunLoopCommonModes];FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"TestNotification" object:nil];FALHTML5中文学习网 - HTML5先行者学习网

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];FALHTML5中文学习网 - HTML5先行者学习网

  });FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)handleMachMessage:(void *)msg {FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock lock];FALHTML5中文学习网 - HTML5先行者学习网

  while ([self.notifications count]) {FALHTML5中文学习网 - HTML5先行者学习网

  NSNotification *notification = [self.notifications objectAtIndex:0];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notifications removeObjectAtIndex:0];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock unlock];FALHTML5中文学习网 - HTML5先行者学习网

  [self processNotification:notification];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock lock];FALHTML5中文学习网 - HTML5先行者学习网

  };FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock unlock];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)processNotification:(NSNotification *)notification {FALHTML5中文学习网 - HTML5先行者学习网

  if ([NSThread currentThread] != _notificationThread) {FALHTML5中文学习网 - HTML5先行者学习网

  // Forward the notification to the correct thread.FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock lock];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notifications addObject:notification];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationLock unlock];FALHTML5中文学习网 - HTML5先行者学习网

  [self.notificationPort sendBeforeDate:[NSDate date]FALHTML5中文学习网 - HTML5先行者学习网

  components:nilFALHTML5中文学习网 - HTML5先行者学习网

  from:nilFALHTML5中文学习网 - HTML5先行者学习网

  reserved:0];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  else {FALHTML5中文学习网 - HTML5先行者学习网

  // Process the notification here;FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"current thread = %@", [NSThread currentThread]);FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"process notification");FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  运行后,其输出如下:FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 23:38:31.637 test[1474:92483] current thread = {number = 1, name = main}FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 23:38:31.663 test[1474:92483] current thread = {number = 1, name = main}FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-11 23:38:31.663 test[1474:92483] process notificationFALHTML5中文学习网 - HTML5先行者学习网

  可以看到,我们在全局dispatch队列中抛出的Notification,如愿地在主线程中接收到了。FALHTML5中文学习网 - HTML5先行者学习网

  这种实现方式的具体解析及其局限性大家可以参考官方文档Delivering Notifications To Particular Threads,在此不多做解释。当然,更好的方法可能是我们自己去子类化一个NSNotificationCenter,或者单独写一个类来处理这种转发。FALHTML5中文学习网 - HTML5先行者学习网

  NSNotificationCenter的线程安全性FALHTML5中文学习网 - HTML5先行者学习网

  苹果之所以采取通知中心在同一个线程中post和转发同一消息这一策略,应该是出于线程安全的角度来考量的。官方文档告诉我们,NSNotificationCenter是一个线程安全类,我们可以在多线程环境下使用同一个NSNotificationCenter对象而不需要加锁。原文在Threading Programming Guide中,具体如下:FALHTML5中文学习网 - HTML5先行者学习网

  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.FALHTML5中文学习网 - HTML5先行者学习网

  NSArrayFALHTML5中文学习网 - HTML5先行者学习网

  ...FALHTML5中文学习网 - HTML5先行者学习网

  NSNotificationFALHTML5中文学习网 - HTML5先行者学习网

  NSNotificationCenterFALHTML5中文学习网 - HTML5先行者学习网

  我们可以在任何线程中添加/删除通知的观察者,也可以在任何线程中post一个通知。FALHTML5中文学习网 - HTML5先行者学习网

  NSNotificationCenter在线程安全性方面已经做了不少工作了,那是否意味着我们可以高枕无忧了呢?再回过头来看看第一个例子,我们稍微改造一下,一点一点来:FALHTML5中文学习网 - HTML5先行者学习网

  代码清单3:NSNotificationCenter的通用模式FALHTML5中文学习网 - HTML5先行者学习网

  @interface Observer : NSObjectFALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  @implementation ObserverFALHTML5中文学习网 - HTML5先行者学习网

  - (instancetype)initFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  self = [super init];FALHTML5中文学习网 - HTML5先行者学习网

  if (self)FALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  _poster = [[Poster alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil]FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  return self;FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)handleNotification:(NSNotification *)notificationFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"handle notification ");FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)deallocFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] removeObserver:self];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  // 其它地方FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];FALHTML5中文学习网 - HTML5先行者学习网

  上面的代码就是我们通常所做的事情:添加一个通知监听者,定义一个回调,并在所属对象释放时移除监听者;然后在程序的某个地方post一个通知。简单明了,如果这一切都是发生在一个线程里面,或者至少dealloc方法是在-postNotificationName:的线程中运行的(注意:NSNotification的post和转发是同步的),那么都OK,没有线程安全问题。但如果dealloc方法和-postNotificationName:方法不在同一个线程中运行时,会出现什么问题呢?FALHTML5中文学习网 - HTML5先行者学习网

  我们再改造一下上面的代码:FALHTML5中文学习网 - HTML5先行者学习网

  代码清单4:NSNotificationCenter引发的线程安全问题FALHTML5中文学习网 - HTML5先行者学习网

  #pragma mark - PosterFALHTML5中文学习网 - HTML5先行者学习网

  @interface Poster : NSObjectFALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  @implementation PosterFALHTML5中文学习网 - HTML5先行者学习网

  - (instancetype)initFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  self = [super init];FALHTML5中文学习网 - HTML5先行者学习网

  if (self)FALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  [self performSelectorInBackground:@selector(postNotification) withObject:nil];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  return self;FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)postNotificationFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  #pragma mark - ObserverFALHTML5中文学习网 - HTML5先行者学习网

  @interface Observer : NSObjectFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  Poster *_poster;FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @property (nonatomic, assign) NSInteger i;FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  @implementation ObserverFALHTML5中文学习网 - HTML5先行者学习网

  - (instancetype)initFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  self = [super init];FALHTML5中文学习网 - HTML5先行者学习网

  if (self)FALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  _poster = [[Poster alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  return self;FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)handleNotification:(NSNotification *)notificationFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"handle notification begin");FALHTML5中文学习网 - HTML5先行者学习网

  sleep(1);FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"handle notification end");FALHTML5中文学习网 - HTML5先行者学习网

  self.i = 10;FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  - (void)deallocFALHTML5中文学习网 - HTML5先行者学习网

  {FALHTML5中文学习网 - HTML5先行者学习网

  [[NSNotificationCenter defaultCenter] removeObserver:self];FALHTML5中文学习网 - HTML5先行者学习网

  NSLog(@"Observer dealloc");FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  #pragma mark - ViewControllerFALHTML5中文学习网 - HTML5先行者学习网

  @implementation ViewControllerFALHTML5中文学习网 - HTML5先行者学习网

  - (void)viewDidLoad {FALHTML5中文学习网 - HTML5先行者学习网

  [super viewDidLoad];FALHTML5中文学习网 - HTML5先行者学习网

  __autoreleasing Observer *observer = [[Observer alloc] init];FALHTML5中文学习网 - HTML5先行者学习网

  }FALHTML5中文学习网 - HTML5先行者学习网

  @endFALHTML5中文学习网 - HTML5先行者学习网

  这段代码是在主线程添加了一个TEST_NOTIFICATION通知的监听者,并在主线程中将其移除,而我们的NSNotification是在后台线程中post的。在通知处理函数中,我们让回调所在的线程睡眠1秒钟,然后再去设置属性i值。这时会发生什么呢?我们先来看看输出结果:FALHTML5中文学习网 - HTML5先行者学习网

  2015-03-14 00:31:41.286 SKTest[932:88791] handle notification beginFALHTML5中文学习网 - HTML5先行者学习网

  2015-03-14 00:31:41.291 SKTest[932:88713] Observer deallocFALHTML5中文学习网 - HTML5先行者学习网

  2015-03-14 00:31:42.361 SKTest[932:88791] handle notification endFALHTML5中文学习网 - HTML5先行者学习网

  (lldb)FALHTML5中文学习网 - HTML5先行者学习网

  // 程序在self.i = 10处抛出了"Thread 6: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)"FALHTML5中文学习网 - HTML5先行者学习网

  经典的内存错误,程序崩溃了。其实从输出结果中,我们就可以看到到底是发生了什么事。我们简要描述一下:FALHTML5中文学习网 - HTML5先行者学习网

  当我们注册一个观察者是,通知中心会持有观察者的一个弱引用,来确保观察者是可用的。FALHTML5中文学习网 - HTML5先行者学习网

  主线程调用dealloc操作会让Observer对象的引用计数减为0,这时对象会被释放掉。FALHTML5中文学习网 - HTML5先行者学习网

  后台线程发送一个通知,如果此时Observer还未被释放,则会向其转发消息,并执行回调方法。而如果在回调执行的过程中对象被释放了,就会出现上面的问题。FALHTML5中文学习网 - HTML5先行者学习网

  当然,上面这个例子是故意而为之,但不排除在实际编码中会遇到类似的问题。虽然NSNotificationCenter是线程安全的,但并不意味着我们在使用时就可以保证线程安全的,如果稍不注意,还是会出现线程问题。FALHTML5中文学习网 - HTML5先行者学习网

  那我们该怎么做呢?这里有一些好的建议:FALHTML5中文学习网 - HTML5先行者学习网

  尽量在一个线程中处理通知相关的操作,大部分情况下,这样做都能确保通知的正常工作。不过,我们无法确定到底会在哪个线程中调用dealloc方法,所以这一点还是比较困难。FALHTML5中文学习网 - HTML5先行者学习网

  注册监听都时,使用基于block的API。这样我们在block还要继续调用self的属性或方法,就可以通过weak-strong的方式来处理。具体大家可以改造下上面的代码试试是什么效果。FALHTML5中文学习网 - HTML5先行者学习网

  使用带有安全生命周期的对象,这一点对象单例对象来说再合适不过了,在应用的整个生命周期都不会被释放。FALHTML5中文学习网 - HTML5先行者学习网

  使用代理。FALHTML5中文学习网 - HTML5先行者学习网

(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助