1

So I'm trying to use GCD in the CLI. To test it out i wrote some code like this:

import Foundation

var i = 0

print("a: ",i)

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {

    for n in 1..<10{
        i++
    }

    print("c: ",i)

    dispatch_async(dispatch_get_main_queue()){
        print("d: ",i)
    }
}

print("b: ",i)

sleep(5)
print("e: ",i)

the output of this is: a: 0 b: 0 c: 9 e: 9

with the last line printing a few seconds later. What I'm trying to find out is what happened at d? Nothing I put in that block seems to execute. This works fine when I use it in iOS, just not in the CLI.

1
  • 1
    the execution terminated before print("d: ",i) has a chance to execute. add to the end your code dispatch_main() to interrupt execution use cmd-c Commented Jan 16, 2016 at 18:41

1 Answer 1

1

The CLI lacks the persistence of an app. It came to an end (terminated) before d had a chance to be printed.

As @user3441734 rightly points out, you can work around this in the CLI by calling dispatch_main() as the last thing before exit. This call effectively forces us to dip into the main queue right now and pull out the main-queued block and execute it, before exiting.

Sign up to request clarification or add additional context in comments.

4 Comments

dispatch_main() is the answer ( this executes blocks submitted to the main queue)
Right you are. This call effectively forces main() to dip into the main queue right now and pull out the queued block and execute it, before exiting. You (or @user3441734) should give this as an answer (and, if it's you, in a couple of days you can accept it): I'll certainly upvote it!
update your answer, please. i am in the middle of nothing (no electricity and my battery will died in minutes ..) if it can helps somebody, that's fine ...
@user3441734 OK, I did that. But the real answer is still yours.

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.