ios - 如果在GCD中为队列创建相同的名称,它是同一个队列吗?

标签 ios swift grand-central-dispatch

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)

我在 Playground 上运行它(Xcode 7.1),结果:

同步:100 异步:100 同步:0 异步:1 等待:100 等待:1

我认为结果应该是:

同步:100 同步:0 异步:100 异步:1 等待:100 等待:1

最佳答案

标签 仅用于记录和调试目的。对于 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.

每次调用 dispatch_queue_create 函数时,您都在创建一个新队列。该队列将在函数退出且最后一个 block 已完成执行后释放,因为您仅将引用保存在局部变量中。

您获得可变输出的原因是两个代码块可以同时执行并且都更新 self.time 属性。有时第一次打印在第二次调用将属性设置为 1 之前执行(因此您得到“10,1”),有时在第一次打印执行之前属性已经设置为 1,因此您得到“1,1”。

关于ios - 如果在GCD中为队列创建相同的名称,它是同一个队列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621621/

相关文章:

ios - 为什么我们需要 visibleCells 函数 (UICollectionView)

ios - 检测点击 UITableViewCell 中的 UIViewCollectionCell

ios - 需要等待 Alamofire 请求完成才能继续 - Swift

swift - 为什么 DispatchSemaphore.wait() 会阻止这个完成处理程序?

iphone - 在 Xcode 中创建两个 iOS 应用程序

ios - 如何将颜色保存到 Realm 并在其他 View Controller 中显示颜色?

ios - UICollectionView 未显示以查看

ios - 无法在 Collection View 中选择项目

linux - 应用程序构建。 (Ubuntu 上的 Swift)

ios - 在Swift中“暂停”游戏