根据维基百科对thread-safety的解释,线程安全代码可以在多线程中运行。
对于iOS 3.x,UIKit不是线程安全,因为4.0,UIKIt是线程安全。
在我们的实现中,我们可以使用synchronized来构建线程安全代码。我关于线程安全的问题是:
1)。如何通过工具或其他方式检测线程安全编码问题? 2)。对于为iOS开发编写线程安全代码,有什么好的实践吗?
发布于 2011-04-26 16:10:25
从
4.0开始,UIKIt是线程安全的。
基本上,UIKit不是线程安全的。从4.0开始,只有在UIKit中绘制图形上下文的图形是线程安全的。
1)嗯,我也想知道:-)
2) Concurrency Programming Guide怎么样?
发布于 2012-12-22 19:37:32
若要使非线程安全的对象线程安全,请考虑使用代理(请参阅下面的代码)。例如,当在后台线程中解析数据时,我将它用于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];
}
@endhttps://stackoverflow.com/questions/5787240
复制相似问题