线程保活
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 线程保活例子<br><br>#import <Foundation/Foundation.h> typedef void (^LXPermenantThreadTask)( void ); @interface LXPermenantThread : NSObject /** 开启线程 默认开启 */ - ( void )run; /** 在当前子线程执行一个任务 */ - ( void )executeTask:(LXPermenantThreadTask)task; /** 结束线程 */ - ( void )stop; @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #import "LXPermenantThread.h" #import "LXProxy.h" /** LXThread **/ @interface LXThread : NSThread @end @implementation LXThread - ( void )dealloc{ NSLog (@ "%s" , __func__); } @end @interface LXPermenantThread() @property (strong, nonatomic ) LXThread *innerThread; @end @implementation LXPermenantThread #pragma mark - public methods - (instancetype)init{ if ( self = [ super init]) { if ( @available (iOS 10.0, *)) { __weak typeof( self )weakSelf = self ; self .innerThread = [[LXThread alloc] initWithBlock:^{ [weakSelf __saveThread]; }]; } else { self .innerThread = [[LXThread alloc]initWithTarget:[LXProxy proxyWithTarget: self ] selector: @selector (__saveThread) object: nil ]; } [ self .innerThread start]; } return self ; } - ( void )run{ if (! self .innerThread) return ; if (! self .innerThread.isExecuting) { [ self .innerThread start]; } } - ( void )executeTask:(LXPermenantThreadTask)task{ if (! self .innerThread || !task) return ; [ self performSelector: @selector (__executeTask:) onThread: self .innerThread withObject:task waitUntilDone: NO ]; } - ( void )stop{ if (! self .innerThread) return ; [ self performSelector: @selector (__stop) onThread: self .innerThread withObject: nil waitUntilDone: YES ]; } - ( void )dealloc{ NSLog (@ "%s" , __func__); [ self stop]; } #pragma mark - private methods -( void )__saveThread{ CFRunLoopSourceContext context = {0}; CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); CFRelease(source); CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, false ); } - ( void )__stop{ CFRunLoopStop(CFRunLoopGetCurrent()); self .innerThread = nil ; } - ( void )__executeTask:(LXPermenantThreadTask)task{ task(); } @end |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库