美文网首页
NSThread 通过 NSRunLoop 完成单线程循环

NSThread 通过 NSRunLoop 完成单线程循环

作者: 公爵海恩庭斯 | 来源:发表于2016-03-25 15:17 被阅读221次

Test.m

创建独立的 thread:

+ (void)testThreadMain {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"test"];
        
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

// 独立线程
+ (NSThread *)testThread {
    static NSThread *testThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        testThread = [[NSThread alloc] initWithTarget:self selector:@selector(testThreadMain) object:nil];
        [testThread start];
    });
    
    return testThread;
}

线程跳转:

- (void)log {
    NSLog(@"current thread: %@", [NSThread currentThread]);
}

// 线程切换,在 main thread 中调用这个方法,切换至 testThread
- (void)test {
    [self performSelector:@selector(log) onThread:[[self class] testThread] withObject:nil waitUntilDone:NO];
}

main.m

循环调用:

#import <Foundation/Foundation.h>
#import "Test.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        for (int i = 0; i < 100; i++) {
            [[[Test alloc] init] test];
        }
        
        [NSThread sleepForTimeInterval:100];
    }
    return 0;
}

结果

打印日志:

...
2016-03-25 15:22:24.270 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
...

参考

深入理解RunLoop

相关文章

  • NSThread 通过 NSRunLoop 完成单线程循环

    Test.m 创建独立的 thread: 线程跳转: main.m 循环调用: 结果 打印日志: 参考 深入理解R...

  • NodeJS单线程为什么可以实现并发

    事件驱动/事件循环 nodejs所谓的单线程,只是主线程是单线程,通过事件循环(event loop)来实现并发操...

  • (转)iOS下的 NSTimer与Run loop Modes

    一.NSRunLoop 在Cocoa中,每个线程(NSThread)对象中内部都有一个run loop(NSRun...

  • NSTimer

    iOS上的每个线程都管理了一个NSRunloop, 字面上看就是通过一个循环来完成一些任务列表。对主线程,这些任务...

  • NSRunloop 简单细说

    NSRunloop简单细说(一)—— 整体了解NSRunloop简单细说(二)—— 获取运行循环及其模式NSRun...

  • NSRunloop

    ### NSRunloop NSRunloop顾名思义,就是一个消息循环,它会侦测输入源(input source...

  • RunLoop

    什么是RunLoop? RunLoop是通过内部维护的事件循环来对事件/消息进行管理的对象。 NSRunLoop是...

  • 避免死循环

    //self.str = @"sdf"; //NSRunLoop会出现循环引用死循环 for(int i = 0;...

  • Flutter之Dart异步实现

    1、Dart是单线程模型 Dart是单线程的,那么如何实现耗时操作呢?Dart是基于单线程加事件循环来完成耗时操作...

  • NSTimer中的NSRunloop

    NSTimer与NSRunloop平时的运用 一, 简单的了解NSRunloop 从字面上看:运行循环、跑圈 其实...

网友评论

      本文标题:NSThread 通过 NSRunLoop 完成单线程循环

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