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),thirdis free to run.Only if you made
MyFunc[sic] anasyncfunction, and did anawaiton theTaskresult, would you be guaranteed to see “Cherry” at the end. Or, obviously, you could movethirdinside theTasks, after theawaitofsecond. But, as it is,thirddoes not need to wait for theTask.“Potato” will always be before “Apple”. The
MyFunchas antry await first(), which means that it will not attempt to runseconduntil the asynchronous tasks offirstare complete.If you did not want
secondto awaitfirst, you could, for example, usewithThrowingTaskGroupand thenaddTaskthose two function calls separately. But as it stands,secondwill not start untilfirstfinishes.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”.
