目标c线程中的线程变量生命周期
Posted
技术标签:
【中文标题】目标c线程中的线程变量生命周期【英文标题】:objective c Thread in Thread variables life time 【发布时间】:2011-06-04 00:50:11 【问题描述】:
我有一个 NSOperation 在它的 -main 方法中我使用[NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];
aObject
(我的 NSOperation 子类的实例变量)是对在 -main 方法内返回的自动释放数组的对象的弱引用...
-(void)main
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *clients = [group produceClients]; // clients array is an autorelease instance
self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!
[NSThread detachNewThreadSelector:@selector(aMethod:)
toTarget:self
withObject:@"I use this for another thing"];
// Do other things here that may take some time
[pool release];
-(void)aMethod:(NSString*)aStr
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// aStr object is reserved for another functionality
// I know that I could pass a NSDictionary with a number of entries, which would be
// retained by `detachNewThreadSelector` but then ...
// I wouldn't have to ask this question ! :)
// Do several things with aObject, which is a weak reference as described above.
NSLog(@"%@", [self->aObject.id]);
// Is it safe ?
[pool release];
我知道 NSThread 的 detachNewThreadSelector 方法保留了self
和 withObject:anArgument
,但是 aObject 会发生什么?是否确定在执行分离线程(aMethod:) 期间会存在? self被detachNewThreadSelector
保留,这是否意味着-main线程的池将被延迟释放,因为它被保留,因此clients
将存在,因此aObject
将存在?
或者-main
(NSOperation) 线程将在-aMethod
(NSThread) 完成之前完成执行并释放,所以在那里使用aObject
是不安全的?
真正的问题是:当从线程内部调用[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]
时,最后一个线程是否保留在其自动释放实例(clients
数组)可以安全用于aMethod
(self->aObject
)(让我们通过弱引用说)?
【问题讨论】:
【参考方案1】:您的方法似乎非常不稳定,但我不是多线程专家,所以我可能是错的。您的客户端数组位于主自动释放池中,您不能保证会等到您的 aMethod 线程完成耗尽。这个呢:
-(void)main
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector:@selector(aMethod:)
toTarget:self
withObject:@"I use this for another thing"];
[pool release];
-(void)aMethod:(NSString*)aStr
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *clients = [group produceClients]; // clients array is an autorelease instance
self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!
[pool release];
使用这种方法,您的客户端数组位于线程的自动释放池中。
【讨论】:
感谢您的回复。我可能会错过提及在self->aObject
设置在-main
线程之前和之后发生的许多事情和处理。所以我希望这两个线程并行执行。否则我不会使用两个线程,对吗?以上是关于目标c线程中的线程变量生命周期的主要内容,如果未能解决你的问题,请参考以下文章