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.

ajbeckner
  • 253
  • 2
  • 8
  • 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 – user3441734 Jan 16 '16 at 18:41

1 Answers1

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • dispatch_main() is the answer ( this executes blocks submitted to the main queue) – user3441734 Jan 16 '16 at 18:46
  • 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! – matt Jan 16 '16 at 19:50
  • 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 Jan 16 '16 at 19:56
  • @user3441734 OK, I did that. But the real answer is still yours. – matt Jan 16 '16 at 21:21