I had assumed that the easy way to ensure serialized access to methods in Swift was to use the new structured concurrency approaches, specifically the actor type.
However, it does not seem to work as expected when the method also uses structured concurrency, i.e. contains async methods.
For example:
actor MyActor {
func doSomething(_ val: Int) async {
print("Started doing something \(val)")
try! await Task.sleep(nanoseconds: 500_000_000)
print("Finished doing something \(val)")
}
}
let actor = MyActor()
for i in 1...5 {
Task { await actor.doSomething(i) }
}
I would have expected this to serialize the code in doSomething, producing pairs of Started N and Finished N. Instead, I get something like:
Started 1
Started 2
Started 3
Finished 2
Finished 1
Finished 3
Given this, it appears to be unblocking access at the first suspension point (e.g. at the Task.sleep()).
Is there an alternative approach I should be using the achieve the desired outcome?
2
1
1.8k