简体   繁体   English

如果在GCD中为队列创建相同的名称,是否是相同的队列?

[英]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? Q1:如果在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: 我在操场上(Xcode 7.1)运行它,结果是:

sync:100 async:100 sync:0 async:1 wait:100 wait:1 同步:100异步:100同步:0异步:1等待:100等待:1

I thin the result should be : 我瘦的结果应该是:

sync:100 sync:0 async:100 async:1 wait:100 wait:1 同步:100同步:0异步:100异步:1等待:100等待:1

The label is just for logging and debugging purposes. label仅用于记录和调试目的。 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. 由于应用程序,库和框架都可以创建自己的调度队列,因此建议使用反向DNS命名方式(com.example.myqueue)。 This parameter is optional and can be NULL. 此参数是可选的,可以为NULL。

You are creating a new queue each time you call the dispatch_queue_create function. 每次调用dispatch_queue_create函数时,您都在创建一个新队列。 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. 您得到可变输出的原因是,两个代码块可能同时执行,并且都更新了self.time属性。 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". 有时,在第二次调用将属性设置为1之前执行第一次打印(因此您将获得“ 10,1”),有时在执行第一次打印之前该属性已被设置为1,因此您将获得“ 1,1”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM