如何正确结束驱动RunLoop的NSThread
来源:互联网 发布:剑三曹雪阳捏脸数据 编辑:程序博客网 时间:2024/05/02 01:08
不负责任的apple sample
Apple的Sample说可以轮循线程是否应该退出,但是有bug
see:documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html
- (void)threadRuntime:(id)arg{ @autoreleasepool { GXLog(@"Thread created............>>>>>>>>>>>>>>>>>>>>>>"); NSRunLoop *rl = [NSRunLoop currentRunLoop]; [_target performSelector:_selector withObject:arg]; [_target release]; _target = nil; BOOL exitNow = NO; NSMutableDictionary *threadDict = [[NSThread currentThread] threadDictionary]; [threadDict setValue:[NSNumber numberWithBool:exitNow] forKey:@"ThreadShouldExitNow"]; NSDate *date = [NSDate date]; while (!exitNow) { [rl runUntilDate:date]; exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue]; } [_thread release]; _thread = nil; GXLog(@"Thread Exited............<<<<<<<<<<<<<<<<<<<<<<"); }}
Instruments进行Time Profile是这样的:
做的题外的修改,如果这样轮询
while (!exitNow) { [rl runUntilDate:[NSDate date]]; exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue]; }
内存占用很恐怖
[NSDate date] autorelease来不及释放,程序最终会因为内存耗尽被系统干掉。
使用CFRunLoopRun/CFRunLoopStop正确结束NSThread
一切皆因轮询而起,那就破了轮询
- (void)threadRuntime:(id)arg{ @autoreleasepool { GXLog(@"Thread created............>>>>>>>>>>>>>>>>>>>>>>"); [_target performSelector:_selector withObject:arg]; [_target release]; _target = nil; CFRunLoopRun(); [_thread release]; _thread = nil; GXLog(@"Thread Exited............<<<<<<<<<<<<<<<<<<<<<<"); }}- (void)stop{ if (!_thread) { return; } CFRunLoopStop(CFRunLoopGetCurrent());}
千万小心,stop会直接停止当前线程得RunLoop,这要求在RunLoop所在的线程执行stop, 实际情况可能在其它线程调用stop。
小结
虽然cocoa&xcode有很多利器,但是能不用多线程还是别用吧。
- 如何正确结束驱动RunLoop的NSThread
- 如何正确结束驱动RunLoop的NSThread
- 多线程:NSThread和runloop
- IOS RUNLOOP NSTHREAD NSOPERationQueue
- NSThread 和 RunLoop
- 如何正确结束Java线程
- 如何选择正确的产品驱动模式?
- 使用runloop阻塞线程的正确写法
- 使用runloop阻塞线程的正确写法
- 使用runloop阻塞线程的正确写法
- iOS 多线程:NSThread和runloop
- 线程的正确结束方式
- iOS runloop 详解3 如何停止子线程的runloop
- mac下在NSThread线程中reloadData的正确方法
- runLoop 添加timer的正确方式 (ios oc)
- 线程池 多线程运行结束后 如何关闭? ExecutorService的正确关闭方法
- 文件结束符eof的正确使用
- 正确结束Java Thread的方法
- Virtual BOX 虚机内的系统显卡增强功能。
- J2EE程序中使用oracle数据库LOB字段的总结(elathen)
- PHPMyAdmin-3.2.5安装详解
- Google将限制Python语言的应用
- js定义数组及相关操作
- 如何正确结束驱动RunLoop的NSThread
- .NET分布式缓存之Memcached执行速度检测
- JAVA程序员应该具备的十项技能【有得学习了】
- HAL module执行过程分析
- 应用程序配置不正确,程序无法启动”详细举例(1)(vc2008 sp1)
- nginx的环境参数配置
- android学习笔记(1)
- 位运算
- 深入理解云存储和云计算-数据模型及实现方式