2011-06-04 37 views
1


我有其中其-main方法內我使用[NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];目標C線程

aObject(我的NSOperation子類的實例變量)是一種弱引用一個autoreleased陣列的對象的的NSOperation該方法 - 主內返回...

-(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陣列)是安全的aMethodself->aObject)所使用的最後一個線程(可以通過弱引用說)?

回答

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]; 
} 

用這種方法,你的客戶端陣列是在線程的autorelease池。

+0

感謝您的回覆。我可能會錯過提到許多事情和處理髮生在'-main'線程中設置'self-> aObject'之前和之後。所以我想要這兩個線程並行執行。我不會使用兩個線程,否則,我? – Vassilis 2011-06-04 01:18:13