Created
November 11, 2020 08:31
-
-
Save ytyubox/b8ec18dae563c0be8288323159ea7b9a to your computer and use it in GitHub Desktop.
2020/11/11 Swift 線上讀書會討論 Deadlock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
這樣用你的 UI 會卡住