I'm running a simulation (SwiftUI app), which has 100 steps.
I need each step to be executed in order.
A first try was to dispatch with delay to schedule each second:
for step in 0..<100 {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(step) * 1.0) {
// simulation code
}
}
Very poor results as 100 running threads are too much load for the system.
So I split in 2 stages:
for bigStep in 0..<10 {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(bigStep) * 10.0 ) {
for step in 0..<10 {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(step) * 1.0) {
// simulation code
}
}
}
}
It works much better, as now there are a max of 20 threads active (in fact I create more levels to limit to a max of 8 concurrent threads).
It addition, it allows to interrupt the simulation before end.
My questions:
- is it the appropriate pattern ?
- Would a timer be better ?
- Other options ?