问题
I'm trying to delay specific threads inside a loop and I am not getting the behavior I want. I would like 1B
to run only once 1A
has been completed, while 2A
runs in parallel on a separate thread. My implementation runs 1A
then 1B
then 2A
instead. Any idea how I can fix this?
Implementation
override func viewDidLoad() {
super.viewDidLoad()
// 1
DispatchQueue.main.async {
self.loopManager(printable: "1A") // 1A
self.loopManager(printable: "1B") // 1B
}
// 2
DispatchQueue.main.async {
self.loopManager(printable: "2A") // 2A
}
}
func loopManager(printable: String) {
for i in 0...3 {
doABC(printable: String(i) + ", " + printable)
sleep(1)
}
}
func doABC(printable: String) {
print(printable)
}
Logs
0, 1A
1, 1A
2, 1A
3, 1A
0, 1B
1, 1B
2, 1B
3, 1B
0, 2A
1, 2A
2, 2A
3, 2A
回答1:
You are running your code in the same thread. You need to run 2A
in another thread.
DispatchQueue.global().async {
self.loopManager(printable: "2A") // 2A
}
Output sample:
0, 1A
0, 2A
1, 2A
1, 1A
2, 1A
2, 2A
3, 1A
3, 2A
0, 1B
1, 1B
2, 1B
3, 1B
来源:https://stackoverflow.com/questions/45527755/synchronizing-issue-with-delays-in-loops