Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

RunLoop – AFP2.x一段源码

2019-11-19 02:37:41

//GCD引进单例
//使用dispatch_once可以简化代码且保证线程安全,开发者无需担心加锁或同步。所有问题都在GCD底层处理
//此外,dispatch_once更高效。它没有使用重量级的同步机制。使用同步机制,每次运行代码都需要获取锁。dispatch_once采用“原子访问”来查询标记,判断代码是否执行过。
+ (NSThread *)threadSingle {
    static NSThread *new = nil;
    static dispatch_once_t *predicate;
    dispatch_once(predicate, ^{
        new = [[NSThread alloc]initWithTarget:self selector:@selector(portRun:) object:nil];
        [new start];
    });
    return new;
}

//常驻线程
+ (void)portRun :(id)__unused object{
    @autoreleasepool {
        [[NSThread currentThread]setName:@"AFP"];
        NSRunLoop *c = [NSRunLoop currentRunLoop];
        [c addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [c run];
    }
}

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *