Notification的多线程安全问题

南峰子这文章给我解惑了。分享给大家。南峰子

Observers and Thread Safety

A friend of mine at Xcoders told me about threading issues with NSNotificationCenter and KVO. In my own code I alwayspost notifications on the main threadand do any KVO-triggering on the main thread (for precisely the reasons he spells out) — so it’s not an issue I’ve run into. But it’s something you should be aware of.

My friend elaborated via email. Below is his email (edited for typography and typos only):

* * *

In most ways that matter NSNotificationCenter is thread safe. You can add/remove observers from any thread and you can post notifications from any thread. You’re on the hook for the thread safety of your observer/selector or block handler, but that’s a pretty reasonable way for the API to work.

Here’s a pretty normal pattern for using notification center:

- (instancetype)init

{

self = [super init];

if (self)

{

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(prompt:) name:@"PromptUserToRateApp" object:];

}

return self;

}

- (void)prompt:(NSNotification *)note

{

// Do something async

}

- (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

and then somewhere else in your code:

[[NSNotificationCenter defaultCenter] postNotificationName:

@"PromptUserToRateApp" object:nil];

This is a perfectly safe thing to do if all those things are happening on the same thread OR if you can guarantee that dealloc will run on the same thread as your -postNotification: calls (or doesn’t run like in the case of singletons.)

Where it gets hinky is when -postNotification: can run on any thread (and therefore so can dealloc because -postNotification: will retain/autorelease it before running.)

Here’s the bug:

Thread 1 calls release taking retainCount down to 0 meaning the object will be dealloced. Your object is dead, is just doesn’t know it yet and there’s no coming back.

Thread 2 comes in and posts a notification, for this case let’s assume synchronously since that’s the common case with the observer/selector API. Observer is retained before calling because notification center keeps an unretained reference to observer and wants to make sure the object is alive. Thing is, you can call retain on an object that’s already in dealloc and that doesn’t stop dealloc from finishing and turning that object into a zombie. So now thread 2 is calling into -prompt: and self is in the middle of becoming garbage so nothing you can do in -prompt: will be safe.

Thread 1 gets into dealloc, the observer gets removed and self becomes garbage rendering anything async you did in -prompt: very dangerous. (Doesn’t even have to be async, but that’s the most pronounced case for this problem.)

This same problem manifests with KVO in a nearly identical way and also with notification centers block based API, although in that case it’s actually the internal __NSObserver object that can end up as the bad object being referenced and there’s the added fact that the observer gets retained and then the block gets scheduled asynchronously so if the scheduling hits while in dealloc, the block will almost certainly run after dealloc has finished.

So what do I do?

There are a few options:

Serialization- Run everything on one thread, not exactly elegant, but it does take a lot of the guess work out. This is actually pretty normal if you’re handling notifications in a view controller posted by system API that promises to run on the main thread. Although, this can fall down pretty easily though because making sure dealloc runs on a specific thread when blocks and autorelease pools exist can be incredibly hard.

Block based API- In practice it’s much harder to hit this issue with the block based API due to the lifetime of the observer object it gives back, but it’s definitely not impossible with some well placed autorelease pools and the block based API is also a snake pit of subtle bugs for many developers.

Objects with safe lifetimes- This issue doesn’t present at all if your target is for example a singleton. Not that I’m suggesting you use more singletons, but if you already have a data controller singleton, it’s a perfectly safe target for threaded notifications.

Don’t use notification center- Ya know what’s great? Weak delegates. The self zeroing weak references in ARC are great and one behavior they offer that’s incredibly useful is that they return nil once an object is going to be dealloced, even before dealloc runs.

This code is totally thread safe:

id delegate = self.delegate;

if ([delegate respondsToSelector:

@selector(prompt:)])

{

[delegate prompt:nil];

}

It’s not strictly required that you use the local ivar, but it’s a good idea since it guarantees that if you get a value back, it will be retained (under ARC) into the local strong variable and live at least through the scope of calling the delegate method.

I’ve always liked delegates. These days I like them even more.

P.S. For people grumbling about how notification center should use weak refs internally, there’s some merit to that, but the unexpected side effects of when weak refs zero can lead to some oddball bugs like if there are multiple observers that are the same except they are registered with different objects (for filtering purposes) and then they all go to zero and you have to decide which one to remove when -removeObserver: is called. It’s not as straightforward as it might seem.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容