IOS開發:Notification與多線程

來源:互聯網
上載者:User

IOS開發: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進行處理呢?或者換個提法,如果我們希望一個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從隊列中移除,並進行處理。

  官方文檔已經給出了範例程式碼,在此借用一下,以測試實際結果:

  代碼清單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和轉寄是同步的),那麼都OK,沒有安全執行緒問題。但如果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對象的引用計數減為0,這時對象會被釋放掉。

  後台線程發送一個通知,如果此時Observer還未被釋放,則會向其轉寄訊息,並執行回調方法。而如果在回調執行的過程中對象被釋放了,就會出現上面的問題。

  當然,上面這個例子是故意而為之,但不排除在實際編碼中會遇到類似的問題。雖然NSNotificationCenter是安全執行緒的,但並不意味著我們在使用時就可以保證安全執行緒的,如果稍不注意,還是會出現線程問題。

  那我們該怎麼做呢?這裡有一些好的建議:

  盡量在一個線程中處理通知相關的操作,大部分情況下,這樣做都能確保通知的正常工作。不過,我們無法確定到底會在哪個線程中調用dealloc方法,所以這一點還是比較困難。

  註冊監聽都時,使用基於block的API。這樣我們在block還要繼續調用self的屬性或方法,就可以通過weak-strong的方式來處理。具體大家可以改造下上面的代碼試試是什麼效果。

  使用帶有安全生命週期的對象,這一點對象單例對象來說再合適不過了,在應用的整個生命週期都不會被釋放。

  使用代理。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.