1

I think that DISPATCH_QUEUE_CONCURRENT will work random, but it seem to work in order.

Is there's something wrong with my code?

code

let concurrentDispatchQueue = dispatch_queue_create("serialDispatchQueue", DISPATCH_QUEUE_CONCURRENT)
func foo(name: String, queue: dispatch_queue_t) {
    for i in 1...10 {
        dispatch_sync(queue) { () -> Void in
            let r = Double(random() % 10)
            NSThread.sleepForTimeInterval(0.02 * r)
            print("\(name) \(i)")
        }
    }
}
foo("concurrent", queue: concurrentDispatchQueue)

output

concurrent 1
concurrent 2
concurrent 3
concurrent 4
concurrent 5
concurrent 6
concurrent 7
concurrent 8
concurrent 9
concurrent 10
aotian16
  • 767
  • 1
  • 10
  • 21

1 Answers1

2

You are dispatching synchronously to the queue. Each

dispatch_sync(queue) { ... }

returns only after the closure has been executed. To test concurrent execution on a queue, change the call to

dispatch_async(queue) { ... }

Note that you have to add

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

if you are testing it in a Playground, see for example How do I run Asynchronous callbacks in Playground.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382