如何将工作线程NSThread封装到C++类中并实现线程退出
解决NSThread无法关闭的问题
原代码的核心问题
- NSThread没有
close方法,你错误使用了不存在的API,正确的线程取消方式是调用cancel标记线程为取消状态,再让线程自身检测状态后主动退出循环。 thread_start方法里的hreadProc是笔误,应为threadProc。- 线程内部的自动释放池处理不规范,循环内未创建临时自动释放池,会导致内存泄漏。
- 取消线程的逻辑未正确触发线程的退出判定。
修正后的完整代码
#include <unistd.h> int threadProc(void* mpClass); struct my_autopool { my_autopool() { pool = [[NSAutoreleasePool alloc] init]; } ~my_autopool() { [pool release]; } NSAutoreleasePool *pool; }; @interface NS_THD : NSObject { @public void* thobj; } @end @implementation NS_THD -(void)thread_start { // 修正笔误:hreadProc -> threadProc threadProc(thobj); } @end class CLS_THD { public: NSThread* mythread; NS_THD *trgt; void CreateThreadOsx(void* mpClass) { my_autopool ap; trgt = [[NS_THD alloc] init]; trgt->thobj = mpClass; mythread = [[NSThread alloc] initWithTarget:trgt selector:@selector(thread_start) object:nil]; [mythread start]; } void ExitThreadOsx() { // 替换不存在的close方法,调用正确的cancel标记线程取消 [mythread cancel]; // 等待线程完全结束,避免资源未释放 [mythread waitUntilDone]; // 清理对象,避免内存泄漏 [mythread release]; [trgt release]; mythread = nil; trgt = nil; } }; class CLS_CPP { CLS_THD th; public: int var_check; CLS_CPP() { printf("Hello CLS_CPP!\n"); var_check = 77; th.CreateThreadOsx((void*)this); } void change() { var_check++; } void exit() { th.ExitThreadOsx(); } }; int threadProc(void* mpClass) { CLS_CPP *pClass = reinterpret_cast<CLS_CPP*>(mpClass); // 循环内每次迭代创建自动释放池,及时清理临时对象 while(![[NSThread currentThread] isCancelled]) { my_autopool loopPool; printf("Check var %d\n", pClass->var_check); usleep(333000); } return 0; }
关键修正点说明
- 正确取消线程:调用
[mythread cancel]会将线程的取消状态设为YES,线程循环中的[[NSThread currentThread] isCancelled]会检测到这个状态,从而退出循环,线程自然结束。 - 自动释放池优化:线程循环内每次迭代创建
my_autopool,确保每次循环产生的临时NS对象被及时释放,避免内存泄漏。 - 资源清理:调用
waitUntilDone等待线程完全终止后,再释放NSThread和NS_THD对象,避免内存泄漏。 - 笔误修正:修复了
hreadProc的拼写错误,确保线程能正确进入执行函数。
内容的提问来源于stack exchange,提问作者Caty
相关产品推荐
相关产品推荐

