Iphone &引用;“只是漏水”;从回调函数执行线程时
我不熟悉iphone编程。任何帮助都将不胜感激:) 当我从obj-c方法或类似以下的c函数中启动新的NSThread时,一切正常:Iphone &引用;“只是漏水”;从回调函数执行线程时,iphone,objective-c,multithreading,Iphone,Objective C,Multithreading,我不熟悉iphone编程。任何帮助都将不胜感激:) 当我从obj-c方法或类似以下的c函数中启动新的NSThread时,一切正常: [NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil]; (thisSelf=self,我使用它可以从C函数中启动线程) 但是,如果我有一个C回调函数,它是从启动这个NSThread的单独C线程调用的(以完全相同的方式),我会得到“NSThread自动
[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil];
(thisSelf=self,我使用它可以从C函数中启动线程)
但是,如果我有一个C回调函数,它是从启动这个NSThread的单独C线程调用的(以完全相同的方式),我会得到“NSThread自动释放,没有池,只是泄漏”
为什么泄漏?我不知道如何避免这种情况,因为在方法“hello”中创建NSAutoreleasePool似乎并不能解决这个问题
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// code of method "hello" here
[pool release];
有什么见解/建议吗?您对hello lloks的实施很好 下一步: 打断任何符号(NSAutoreleaseNoPool?)并告诉我:这是从哪个线程调用的 我怀疑在创建辅助线程的线程中可能没有设置自动释放池 如果不是,并且是新线程,那么您没有足够早地创建自动释放池
(如果这不能解决问题,更多的代码会有帮助)尝试以这种方式进行更改:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil];
[pool drain];
问题在于,
+detachNewThreadSelector:…
创建了一个自动释放的NSThread对象,因此发送该消息的单独C线程也需要一个自动释放池。可以通过显式创建NSThread对象来避免这种情况:
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
尽管init方法的内部可能也需要一个自动释放池,在这种情况下,您只需创建一个
如果您正在使用posix线程创建C线程,则在启动第一个posix线程时会遇到一个问题。与发布问题相关: