Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

swift - Nothing prints out in the console in command line tool Xcode

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...