NSNotification 竞争条件
-
22-09-2019 - |
题
在单线程中使用 NSNotifications 时是否存在竞争条件问题?这是一个示例方法:
- (void) playerToggled: (NSNotification *) notification {
if (timerPane.playing && ! timerPane.paused) {
[playerPane toggleCurrentPlayer];
[timerPane toggleTimer];
[mainPane playerToggled];
}
}
条件之后的前两个调用将触发 mainPane 接收的 NSNotifications。mainPane 是否保证在这些通知后收到playerToggled 消息?我应该说这段代码似乎按预期工作(playerToggled 总是最后执行)。但我不确定通知存在哪些时间问题,而且我找不到具体的答案。
解决方案
我不太清楚你的意思,但我认为这会对你有所帮助:
尤其是这一部分:使用 NSNotificationCenter 的 postNotification:方法及其变体,您可以将通知发布到通知中心。但是,该方法的调用是同步的:在发布对象可以恢复其执行线程之前,它必须等待通知中心将通知分派给所有观察者并返回。
其他提示
有没有竞争条件可以预期的。除了丹·唐纳森的答案,这里是从文档的NSNotificationCenter另一句名言:
一个通知中心提供通知观察者同步。换句话说,在postNotification:方法不返回,直到所有的观察家都接收和处理的通知。发送通知异步地使用NSNotificationQueue。
不隶属于 StackOverflow