Why this thread doesn't execute last line code

42 Views Asked by At

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'.

1

There are 1 best solutions below

0
Sulthan On BEST ANSWER

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.