如果我有一个自动释放的对象并且我需要将它提供给不同的线程,最好的方法是什么?
假设我有一个在线程 0 中自动释放的对象。我将这个对象告诉线程 1,它保留了它,因为它需要它。后来它完成了,它释放了它。没问题。当线程 0 再次运行并清空其自动释放池时,它会看到保留计数为 1,并且因为它是一个自动释放对象,所以它会释放。一切都很好,因此线程无关紧要。对吧?
顺便说一句,这本来是一道面试题。面试官坚持不能将自动释放的对象交给另一个线程。他似乎为此生气了。在技术面试中,我越来越多地遇到自认为无所不知的人。
最佳答案
您不应该将自动释放的对象直接传递给其他线程。
在这段代码中
id _sharedVariable; // ivar
NSConditionLock *_lock;
- (void)thread1
{
id objectNeedToPass = [[NSObject new] autorelease];
[_lock lock];
_sharedVariable = objectNeedToPass;
[_lock unlockWithCondition:1];
}
- (void)thread2
{
while (true)
{
[_lock lockWithCondition:1];
id objectReceived = [_sharedVariable retain];
[_lock unlockWithCondition:0]
process(objectReceived );
[objectReceived release];
}
}
线程 2 可能会看到 _sharedVariable
持有已释放的对象(并崩溃)
因为它可能会这样做
thread 1 create and autorelease object
thread 1 assign it to the shared variable
thread 1 release the object
object deallocated
thread 2 read the object
thread 2 retain the object - crash
要解决这个问题,你应该传递一个保留的对象
id _sharedVariable; // ivar
NSConditionLock *_lock;
- (void)thread1
{
id objectNeedToPass = [[NSObject new] autorelease];
[_lock lock];
_sharedVariable = [objectNeedToPass retain];
[_lock unlockWithCondition:1];
}
- (void)thread2
{
while (true)
{
[_lock lockWithCondition:1];
id objectReceived = _sharedVariable;
[_lock unlockWithCondition:0]
process(objectReceived );
[objectReceived release];
}
}
但是,如果第二个线程未能释放对象并使代码难以维护(保留/释放很难平衡),这可能会导致内存泄漏
关于ios - objective-c : Autoreleased objects between threads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802509/