【问题标题】:thread safe in iOS developmentiOS开发中的线程安全
【发布时间】:2011-04-26 07:25:41
【问题描述】:

来自关于thread-safety 的维基百科解释,线程安全代码可以在多线程中运行。

对于 iOS 3.x,UIKit 不是线程安全的,因为 4.0,UIKit 是线程安全的。

在我们的实现中,我们可以使用同步来构建线程安全代码。我关于线程安全的问题是:

1)。如何使用仪器工具或其他方式检测线程安全编码问题? 2)。为 iOS 开发编写线程安全代码有什么好的做法吗?

【问题讨论】:

标签: multithreading ios uikit thread-safety


【解决方案1】:

从 4.0 开始,UIKI 是线程安全的。

基本上,UIKit 不是线程安全的。从 4.0 开始,只有 在 UIKit 中绘制到图形上下文 是线程安全的。

1) 嗯,我也想知道 :-)

2) Concurrency Programming Guide怎么样?

【讨论】:

    【解决方案2】:

    要使非线程安全对象线程安全,请考虑使用代理(参见下面的代码)。例如,在后台线程中解析数据时,我将它用于 NSDateFormatter,它不是线程安全的类。

    /**
     @brief
     Proxy that delegates all messages to the specified object
     */
    @interface BMProxy : NSProxy {
        NSObject *object;
        BOOL threadSafe;
    }
    
    @property(atomic, assign) BOOL threadSafe;
    
    - (id)initWithObject:(NSObject *)theObject;
    - (id)initWithObject:(NSObject *)theObject threadSafe:(BOOL)threadSafe;
    
    @end
    
    @implementation BMProxy
    
    @synthesize threadSafe;
    
    - (id)initWithObject:(NSObject *)theObject {
        object = [theObject retain];
        return self;
    }
    
    - (id)initWithObject:(NSObject *)theObject threadSafe:(BOOL)b {
        if ((self = [self initWithObject:theObject])) {
            self.threadSafe = b;
        }
        return self;
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
        return [object methodSignatureForSelector:aSelector];
    }
    
    - (void)forwardInvocation:(NSInvocation *)anInvocation {
        if (self.threadSafe) {
            @synchronized(object) {
                [anInvocation setTarget:object];
                [anInvocation invoke];
            }
        } else {
            [anInvocation setTarget:object];
            [anInvocation invoke];
        }
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
        BOOL responds = [super respondsToSelector:aSelector];
        if (!responds) {
            responds = [object respondsToSelector:aSelector];
        }
        return responds;
    }
    
    - (void)dealloc {
        [object release];
        [super dealloc];
    }
    
    @end
    

    【讨论】:

    • 把它变成NSObject上的一个类别。 };)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2014-08-29
    • 2017-05-14
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多