gpt4 book ai didi

ios - 信号量在执行它之后的代码块之前不会等待

转载 作者:可可西里 更新时间:2023-11-01 00:53:24 27 4
gpt4 key购买 nike

我在使用信号量方面还很陌生,所以我不确定自己是否正确使用了它。

当我尝试这样做时:

var group = dispatch_group_create();
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)){

var myRef = self.userRef.childByAppendingPath(self.userRef.authData.uid)
myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
// do some stuff once
println("WE ARE IN HERE")
firstName = snapshot.value["firstName"] as String!
lastName = snapshot.value["lastName"] as String!
})
}
dispatch_semaphore_wait(group, DISPATCH_TIME_FOREVER)
dispatch_semaphore_signal(group)
println("WE MADE IT OUT OF THERE")

输出总是:

"WE MADE IT OUF OF THERE"
"WE ARE IN HERE"

为什么它不等待我的信号量完成后再执行其余代码?

编辑:

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> () in
// do some task
var myRef = self.userRef.childByAppendingPath(self.userRef.authData.uid)
myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
// do some stuff once
println("WE ARE IN HERE")
firstName = snapshot.value["firstName"] as String!
lastName = snapshot.value["lastName"] as String!
})
});

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> () in
// do some task
var standbyData = [
"firstName":firstName,
"lastName":lastName,
"duration":self.helpDurationLabel.text!,
"radius":self.helpRadiusLabel.text!,
"categories": categories,
"time_stamp":self.date.timeIntervalSince1970
]
println("WE ARE OUT HERE")
var standbyUserRef = self.standbyRef.childByAppendingPath(self.userRef.authData.uid)
standbyUserRef.updateChildValues(standbyData)
});

既然我将 2 个同步线程放在同一个队列中,这不应该工作吗?

最佳答案

你在这里混淆了几个概念——调度组和信号量用于不同的目的。您需要 (1) 创建一个信号量,(2) 在您的 block 中,向信号量发出信号,以及 (3) 在 block 外等待信号量:

注意:这会在等待时阻塞它正在运行的任何线程,因此如果它在主线程上,它将暂停用户交互——这不是一个好主意。您最好阅读 Apple 的 Concurrency Programming Guide理解其余的概念。

var semaphore = dispatch_semaphore_create(0)
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)){
var myRef = self.userRef.childByAppendingPath(self.userRef.authData.uid)
myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
// do some stuff once
println("WE ARE IN HERE")
firstName = snapshot.value["firstName"] as String!
lastName = snapshot.value["lastName"] as String!
})
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
println("WE MADE IT OUT OF THERE")

关于ios - 信号量在执行它之后的代码块之前不会等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28522853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com