2

I am having some trouble understanding dispatch.async. I have the following code:

dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)) {
    print("hello")
    print("world")
    dispatch_async(dispatch_get_main_queue()) {
        print("done")
    }
}

Yet the only thing that it printed out is:

hello

No matter what I do, only the first line is executed. If I replace it with a function, like so:

func printHelloWorld(){
    print("hello")
    print("world")
}

dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)) {
    printHelloWorld()
    dispatch_async(dispatch_get_main_queue()) {
        print("done")
    }
}

The same thing happened. The function is called, but the only the first line of executable code is run. In addition, the closure to be called when the thread finished is not being called at all.

Any help understanding how to use dispatch.async would be greatly appreciated.

2
  • i just added it to my project and my log shows hello world done Commented Jan 12, 2016 at 4:14
  • Is it possible that it is because it is being run in playground? Commented Jan 12, 2016 at 4:15

1 Answer 1

3

Playgrounds stop executing once the main thread is done running top level code. You can use this line of code to keep the playground running if you're running asynchronous code:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

And then use this line of code once you're done:

XCPlaygroundPage.currentPage.finishExecution()
Sign up to request clarification or add additional context in comments.

5 Comments

Is this applicable for all programs? For example, if I am running a Swift program from the Terminal, must I make sure that the main thread continues so that the background thread is not ended prematurely?
The same thing was happening in Terminal. I had to make sure the main thread was kept open for long enough.
Yeah, that's correct. "Regular" apps (i.e. GUI apps for e.g. iOS or OS X) spin an NSRunLoop to stay alive indefinitely.
How would I achieve the same effect in a Swift program being run from the Terminal?
@Acoop the simplest way would be to just add NSRunLoop.currentRunLoop().run() after all top level code which just spins forever (until you call exit() or abort or fatal error etc). If you run into problems or you have more complex requirements, read developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.