I'm trying to figure out, what actor brings to use. It's not clear for me - are they truly parallel or just concurrent.
I did little test to check myself:
actor SomeActor {
func check() {
print("before sleep")
sleep(5)
print("after sleep")
}
}
let act1 = SomeActor()
let act2 = SomeActor()
Task {
await withTaskGroup(of: Void.self) { group in
group.addTask {
await act1.check()
}
group.addTask {
await act2.check()
}
}
}
Output is:
before sleep // Waiting 5 sec
after sleep
before sleep // Starting after 5 sec
after sleep
I block current executor thread so it doesn't yield it. But second task doesn't start in parallel.
So does it mean that each instance of the same actor type share executor instance?
If so then multiple instance of same actor don't support truly parallelism, but concurrent execution?
UPD:
I have a little bit new observations. So example above use inherited isolation when we run group.add(). So it can't pass second actor call immediately.
My second observation - when we run tasks this way:
let act1 = SomeActor()
let act2 = SomeActor()
Task.detached {
await act1.check()
}
Task { @MainActor in
await act2.check()
}
Output is:
before sleep
before sleep
after sleep
after sleep
So it's truly parallel
But when I use detached task, output is serial the same:
let act1 = SomeActor()
let act2 = SomeActor()
Task.detach {
await act1.check()
}
Task.detached { @MainActor in
await act2.check()
}
Output is:
before sleep
after sleep
before sleep
after sleep