双重检查锁定 - 目标 c
我意识到由于内存模型,双重检查锁定在 Java 中存在缺陷,但这通常与单例模式和优化单例的创建相关。
在 Objective-c 中的这种情况下怎么样:
我有一个布尔标志来确定我的应用程序是否正在流式传输数据。我有 3 个方法,startStreaming、stopStreaming、streamingDataReceived,并且我使用以下方法保护它们免受多个线程的影响:
- (void) streamingDataReceived:(StreamingData *)streamingData {
if (self.isStreaming) {
@synchronized(self) {
if (self.isStreaming) {
- (void) stopStreaming {
if (self.isStreaming) {
@synchronized(self) {
if (self.isStreaming) {
- (void) startStreaming:(NSArray *)watchlistInstrumentData {
if (!self.isStreaming) {
@synchronized(self) {
if (!self.isStreaming) {
此双重检查是否不必要?双重检查在objective-c中是否有与java中类似的问题?此模式(反模式)的替代方案是什么?
谢谢
I realised double checked locking is flawed in java due to the memory model, but that is usually associated with the singleton pattern and optimizing the creation of the singleton.
What about under this case in objective-c:
I have a boolean flag to determine if my application is streaming data or not. I have 3 methods, startStreaming, stopStreaming, streamingDataReceived and i protect them from multiple threads using:
- (void) streamingDataReceived:(StreamingData *)streamingData {
if (self.isStreaming) {
@synchronized(self) {
if (self.isStreaming) {
- (void) stopStreaming {
if (self.isStreaming) {
@synchronized(self) {
if (self.isStreaming) {
- (void) startStreaming:(NSArray *)watchlistInstrumentData {
if (!self.isStreaming) {
@synchronized(self) {
if (!self.isStreaming) {
Is this double check uneccessary? Does the double check have similar problems in objective-c as in java? What are the alternatives to this pattern (anti-pattern).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它同样有缺陷 - 你有一个竞争条件
你必须输入你的同步部分,然后检查标志
It is equally flawed - you have a race condition
You have to enter your synchronized section and then check the flag
对我来说,这看起来像是过早的优化。有什么问题(例如)
That looks like premature optimisation to me. What's wrong with (for example)