Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Created November 11, 2020 08:31
Show Gist options
  • Save ytyubox/b8ec18dae563c0be8288323159ea7b9a to your computer and use it in GitHub Desktop.
Save ytyubox/b8ec18dae563c0be8288323159ea7b9a to your computer and use it in GitHub Desktop.
2020/11/11 Swift 線上讀書會討論 Deadlock
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setMainQueueKey()
}
@IBAction func trigger(_ sender: Any) {
let list = (6...10).map(\.description)
var captured = [String]()
let group = DispatchGroup()
assert(isMainQueue())
for s in list {
print(s," start")
group.enter()
assert(isMainQueue())
delayWork { [group] in
print(s, "finished")
captured.append(s)
group.leave()
}
assert(isMainQueue())
group.wait()
}
assert(isMainQueue())
group.notify(queue: .main) {
print("captured.count == ", captured.count)
}
}
}
func delayWork(then: @escaping () -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
then()
}
}
let key = DispatchSpecificKey<UInt>()
func setMainQueueKey() {
DispatchQueue.main.setSpecific(key: key, value: UInt(1))
}
func isMainQueue() ->Bool {
DispatchQueue.getSpecific(key: key) == UInt(1)
}
@ytyubox
Copy link
Author

ytyubox commented Nov 11, 2020

IMG_FB147258D465-1

這樣用你的 UI 會卡住

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment