I'm newbie. When I run this code, I catch Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) Help pls, what's wrong?
func first() async throws {
try await Task.sleep(nanoseconds: 100)
print("Potato")
}
func second() async throws {
try await Task.sleep(nanoseconds: 1)
print("Apple")
}
func third(){
print("Cherry")
}
func MyFunc() {
Task {
print("Banana")
try await first()
try await second()
print("Onion")
}
third()
}
MyFunc()
CodePudding user response:
You said:
When I run this code, I catch Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
The above is insufficient to manifest that problem. It works for me in both an App and a Playground. Where did you have this code? If playground, make sure to
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
If you are still having trouble, please provide more details of precisely the environment and steps you took to produce this crash.
You said:
The program should output sequentially: Banana -> Apple -> Potato -> Onion -> Cherry
A few observations:
You should not expect “Cherry” to be at the end. The
Task { … }
runs asynchronously. As soon as it hits a suspension point (aka, anawait
),third
is free to run.Only if you made
MyFunc
[sic] anasync
function, and did anawait
on theTask
result, would you be guaranteed to see “Cherry” at the end. Or, obviously, you could movethird
inside theTasks
, after theawait
ofsecond
. But, as it is,third
does not need to wait for theTask
.“Potato” will always be before “Apple”. The
MyFunc
has antry await first()
, which means that it will not attempt to runsecond
until the asynchronous tasks offirst
are complete.If you did not want
second
to awaitfirst
, you could, for example, usewithThrowingTaskGroup
and thenaddTask
those two function calls separately. But as it stands,second
will not start untilfirst
finishes.When I run this in an app, I see Cherry » Banana » Potato » Apple » Onion. Or in Playground, I see Banana » Cherry » Potato » Apple » Onion. Both of these sequences are perfectly viable responses.
But either way, you should expect neither “Cherry” at the end nor “Apple” before “Potato”.