开发者

"Just Leaking" when Threading from a Callback Function

I am new to iphone programming. Any help will be greatly appreciated :)

All is ok when I start a new NSThread from within an obj-c method or a C function like this:

[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil];

(thisSelf=self, i use this to be able to start the thread from within a C function)

However, if I have a C callback function that is called from a separate C thread starting this NSThread instead (in the exact same way), I get "NSThread autoreleased with no pool in place - just leaking"

Why the leak? I cannot figure out how to avoid this, since creating an NSAutoreleasePool in method "hello" does not seem to solve this.

开发者_如何学JAVANSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// code of method "hello" here  
[pool release];

Any insights/suggestions?


The problem is that +detachNewThreadSelector:... creates an autoreleased NSThread object, so your separate C thread that sends that message needs an autorelease pool too. You can avoid this by explicitly creating the NSThread object:

NSThread* newThread = [[NSThread alloc] initWithTarget: thisSelf 
                                              selector: @selector(hello) 
                                                object: nil];
[newThread start];
[newThread release];  // this might not be OK.  You might need to wait until the thread is finished

although, the internals of the init method might need an autorelease pool too in which case, you'll just have to create one.

If you are creating your C thread using posix threads, you have a problem in that you need to notify the Cocoa framework that the application is now multithreaded when you start your first Posix thread.


your implementation of hello lloks fine.

next:

break on whatever symbol that is (NSAutoreleaseNoPool?) and tell me: which thread is this called from?

i suspect you may not have an autorelease pool set up in the thread which you create the secondary thread in.

if not, and it's the new thread, then you're not creating the autorelease pool early enough.

(more code would help if that doesn't solve it for you)


Try to change this way:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil];
[pool drain];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜