Trying to implement basic concurrent code with actors

You can kind of control the width of the TaskGroup by only enqueuing a certain number of tasks up front and then enqueuing more as some of that group completes.

import CoreFoundation

@main
struct ConcurrencyTest {
    static func main() async {
        let start = CFAbsoluteTimeGetCurrent()
        await withTaskGroup(of: Void.self) { group in
            @Sendable
            func doNothing() {}
            
            var tasksToPerform = 49_990
            for _ in 0..<10 {
                group.addTask {
                    doNothing()
                }
            }
            
            for await _ in group {
                if tasksToPerform > 0 {
                    group.addTask { doNothing() }
                    tasksToPerform -= 1
                }
            }
        }
        print(CFAbsoluteTimeGetCurrent() - start)
    }
}

Hilariously, in this case it reduced my overall runtime from ~8.6s to 0.059s.

5 Likes