Search code examples
iosnsrunloop

Why this thread doesn't execute last line code


I create a thread. And I find this thread doesn't execute last line code.

let thread = Thread {
    RunLoop.current.add(NSMachPort(), forMode: RunLoopMode.commonModes)
    let runloop = CFRunLoopGetCurrent()
    print("A")
    CFRunLoopRun()
    print("B")
}

Then I invoke this thread 'thread.start()'. But it only can print 'A'.


Solution

  • CFRunLoop() is a function that runs indefinitely, until it is stopped. That means the above code is basically:

    print("A")
    while true {
      // execute run loop 
    }
    print("B")
    

    The last line cannot be called until you stop the run loop.