func oneAsynTask(callback: @escaping (Int)->Void) {
DispatchQueue.global().async {
print("task running")
sleep(5)
callback(5)
print("task finsh")
}
}
way1
func waitToFinishWay1() {
/// 信号量实现
DispatchQueue.global().async {
let semp = DispatchSemaphore(value: 0)
var returnValue: Int = 0
self.oneAsynTask { value in
returnValue = value
semp.signal()
}
print("waiting ...")
semp.wait()
print("waiting finsh")
print("returnValue:\(returnValue)")
}
}
way2
func waitToFinishWay2() {
DispatchQueue.global().async {
var returnValue: Int = 0
let condition = NSCondition()
condition.lock()
self.oneAsynTask { value in
returnValue = value
condition.signal()
}
print("waiting ...")
while returnValue == 0 { // 加这个,是为了可能还没有开始等待,上面的异步任务已经完成
condition.wait()
}
condition.unlock()
print("waiting finsh")
print("returnValue:\(returnValue)")
}
}
way3
func waitTOFinishWay3() {
DispatchQueue.global().async {
var returnValue: Int = 0
let group = DispatchGroup()
group.enter()
self.oneAsynTask { value in
returnValue = value
group.leave()
}
print("waiting ...")
group.wait()
print("waiting finsh")
print("returnValue:\(returnValue)")
}
}
way4
func waitToFinshWay4() {
DispatchQueue.global().async {
var returnValue: Int = 0
let group = DispatchGroup()
group.enter()
self.oneAsynTask { value in
returnValue = value
group.leave()
}
print("waiting ...")
while returnValue == 0 {
}
print("waiting finsh")
print("returnValue:\(returnValue)")
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)