美文网首页
常驻线程

常驻线程

作者: 阿凡提说AI | 来源:发表于2018-12-27 21:45 被阅读17次

    当创建一个线程,并且希望它一直存在时,但往往我们创建的线程都是执行完成之后也就停止了,不能再次利用,那么如何创建一个线程可以让他可以再次工作呢,这个时候就需要使用到RunLoop了。
    1.OC语言实现

    #import <Foundation/Foundation.h>
    
    typedef void (^PermenantThreadTask)(void);
    
    @interface PermenantThread : NSObject
    
    /**
     开启线程
     */
    //- (void)run;
    
    /**
     在当前子线程执行一个任务
     */
    - (void)executeTask:(PermenantThreadTask)task;
    
    /**
     结束线程
     */
    - (void)stop;
    
    @end
    
    
    #import "PermenantThread.h"
    
    
    
    /** PermenantThread **/
    @interface PermenantThread()
    @property (strong, nonatomic) NSThread *innerThread;
    @property (assign, nonatomic, getter=isStopped) BOOL stopped;
    @end
    
    @implementation PermenantThread
    #pragma mark - public methods
    - (instancetype)init
    {
        if (self = [super init]) {
            self.stopped = NO;
            
            __weak typeof(self) weakSelf = self;
            
            self.innerThread = [[NSThread alloc] initWithBlock:^{
                [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
                
                while (weakSelf && !weakSelf.isStopped) {
                    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
                }
            }];
            
            [self.innerThread start];
        }
        return self;
    }
    
    - (void)executeTask:(PermenantThreadTask)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)__stop
    {
        self.stopped = YES;
        CFRunLoopStop(CFRunLoopGetCurrent());
        self.innerThread = nil;
    }
    
    - (void)__executeTask:(PermenantThreadTask)task
    {
        task();
    }
    
    @end
    
    

    2.C语言实现

    #import <Foundation/Foundation.h>
    
    typedef void (^PermenantThreadTask)(void);
    
    @interface PermenantThread : NSObject
    
    /**
     开启线程
     */
    //- (void)run;
    
    /**
     在当前子线程执行一个任务
     */
    - (void)executeTask:(PermenantThreadTask)task;
    
    /**
     结束线程
     */
    - (void)stop;
    
    @end
    
    
    
    
    
    #import "PermenantThread.h"
    
    
    /** PermenantThread **/
    @interface PermenantThread()
    @property (strong, nonatomic) NSThread *innerThread;
    @end
    
    @implementation PermenantThread
    #pragma mark - public methods
    - (instancetype)init
    {
        if (self = [super init]) {
            self.innerThread = [[NSThread alloc] initWithBlock:^{
                NSLog(@"begin----");
                
                // 创建上下文(要初始化一下结构体)
                CFRunLoopSourceContext context = {0};
                
                // 创建source
                CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
                
                // 往Runloop中添加source
                CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
                
                // 销毁source
                CFRelease(source);
                
                // 启动
                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, false);
                
    //            while (weakSelf && !weakSelf.isStopped) {
    //                // 第3个参数:returnAfterSourceHandled,设置为true,代表执行完source后就会退出当前loop
    //                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
    //            }
                
                NSLog(@"end----");
            }];
            
            [self.innerThread start];
        }
        return self;
    }
    
    //- (void)run
    //{
    //    if (!self.innerThread) return;
    //
    //    [self.innerThread start];
    //}
    
    - (void)executeTask:(PermenantThreadTask)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)__stop
    {
        CFRunLoopStop(CFRunLoopGetCurrent());
        self.innerThread = nil;
    }
    
    - (void)__executeTask:(PermenantThreadTask)task
    {
        task();
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:常驻线程

          本文链接:https://www.haomeiwen.com/subject/mttjlqtx.html