Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it the same queue if create the same name for queue in GCD?

Q1:Is it the same queue if create the same name for queue in GCD?

class Sample {
private var time:Int64 = 0
func asyncSerial(time:Int64){
    let queue = dispatch_queue_create("test",DISPATCH_QUEUE_SERIAL)

    dispatch_async(queue){
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, time)
        self.time = time
        print("async:\(self.time)")

        dispatch_after(delayTime, queue){
            print("wait:\(self.time)")

        }
    }

    print("sync:\(self.time)")
}
}

let s = Sample()
s.result(10)
let s2 = Sample()
s1.result(1)

I run it in playground(Xcode 7.1),and result:

sync:100 async:100 sync:0 async:1 wait:100 wait:1

I thin the result should be :

sync:100 sync:0 async:100 async:1 wait:100 wait:1

like image 865
Leo Avatar asked Dec 30 '25 01:12

Leo


1 Answers

The label is just for logging and debugging purposes. For the documentation:

A string label to attach to the queue to uniquely identify it in debugging tools such as Instruments, sample, stackshots, and crash reports. Because applications, libraries, and frameworks can all create their own dispatch queues, a reverse-DNS naming style (com.example.myqueue) is recommended. This parameter is optional and can be NULL.

You are creating a new queue each time you call the dispatch_queue_create function. This queue will be released after the function exits and the last block has completed execution since you are only holding the reference in a local variable.

The reason you get a variable output is that both blocks of code may execute concurrently and both update the self.time property. Sometimes the first print executes before the second invocation has set the property to 1 (so you get "10,1") and sometimes the property has already been set to 1 before the first print executes, so you get "1,1".

like image 136
Paulw11 Avatar answered Dec 31 '25 13:12

Paulw11