1

Nothing prints out in the console in command line tool Xcode when I run the following code:

import Foundation

class A {
  var someValue = 0

  let concurrentQueue = dispatch_queue_create("queue_for_property", DISPATCH_QUEUE_CONCURRENT)

  func increaseValueBy1000() {
    dispatch_barrier_async(concurrentQueue) {
      for _ in 0 ..< 1000 {
        let v = self.someValue + 1
        print(v)
        self.someValue = v
      }
    }
  }
}

let instance1 = A()

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
  instance1.increaseValueBy1000()
}

instance1.increaseValueBy1000()

I don't see any print statement in the console. If I remove barrier line works pretty fine. What I do wrong in this case why my barriers don't allow to print?

1 Answer 1

6

Applications – such has command-line programs – which do not already have a "run loop" have to call

dispatch_main() // Swift 2
dispatchMain()  // Swift 3

in order to use GCD. From the documentation:

This function "parks" the main thread and waits for blocks to be submitted to the main queue. Applications that call UIApplicationMain (iOS), NSApplicationMain (Mac OS X), or CFRunLoopRun on the main thread must not call dispatch_main.

7
  • Thank you, can you explain in what part I should call it?
    – wm.p1us
    May 5, 2016 at 6:43
  • 1
    @wm.p1us: At the end of your program. See also developer.apple.com/legacy/library/documentation/Darwin/….
    – Martin R
    May 5, 2016 at 6:43
  • Thank you! Works like a charm! But if I remove barrier I got duplication values but not race condition. Because values are not rewritten.
    – wm.p1us
    May 5, 2016 at 6:44
  • i am facing the same problem in my command line tool created in swift language. What needs to be done? the above link is invalid for apple developer forum. Please explain the solution.
    – Tejas
    Jul 23, 2019 at 7:24
  • @Tejas: I have added a link to the current documentation.
    – Martin R
    Jul 23, 2019 at 7:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.