2011-02-15 44 views
1

我是iphone编程的新手。任何帮助将不胜感激:)当从回调函数中执行线程时发生“Just Leaking”

一切正常,当我从一个OBJ-C方法或这样的C函数内启动一个新的NSThread:

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

(thisSelf =自我,我使用这以便能够从一个C函数启动线程)

但是,如果我有一个C调用从一个单独的C线程启动此NSThread而不是(以完全相同的方式)调用的函数,我得到“NSThread自动释放,没有到位 - 只是泄漏“

为什么泄漏?我无法弄清楚如何避免这种情况,因为在“hello”方法中创建一个NSAutoreleasePool似乎并不能解决这个问题。

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
// code of method "hello" here 
[pool release]; 

任何见解/建议?

回答

3

的问题是,+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线程时需要notify the Cocoa framework that the application is now multithreaded

+0

相关的释放问题:http://stackoverflow.com/questions/1151637/when-is-it-safe-to-release-an-nsthread – Chuck 2011-02-15 18:31:16

0

你的执行你好lloks罚款。

未来

上任何符号,它是(?NSAutoreleaseNoPool),并告诉我休息:哪个线程这个从叫什么?

我怀疑你可能不会有一个自动释放池在其中创建在辅助线程的线程设置。

如果没有,它是线程,那么你没有创建自动释放池早就够了。

(更多的代码,将有助于如果不解决这个问题你)

0

试图改变这样:

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

这实际上也消除了泄漏。谢谢 – ntcio 2011-02-15 21:02:14

相关问题