objective c Thread in Thread变量的生命周期

时间:2011-06-04 00:50:12

标签: objective-c nsthread nsautoreleasepool lifetime


我有一个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数组)可以安全地用于{{1 (aMethod)(假设通过弱引用)?

1 个答案:

答案 0 :(得分:0)

你的方法似乎非常不稳定,但我不是多线程的专家,所以我可能是错的。您的客户端数组位于主自动释放池中,您不能确定它将等到您的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];
}

使用这种方法,您的clients数组位于线程的自动释放池中。