Home > front end >  Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) with simple async funcs
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) with simple async funcs

Time:06-14

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, an await), third is free to run.

    Only if you made MyFunc [sic] an async function, and did an await on the Task result, would you be guaranteed to see “Cherry” at the end. Or, obviously, you could move third inside the Tasks, after the await of second. But, as it is, third does not need to wait for the Task.

  • “Potato” will always be before “Apple”. The MyFunc has an try await first(), which means that it will not attempt to run second until the asynchronous tasks of first are complete.

    If you did not want second to await first, you could, for example, use withThrowingTaskGroup and then addTask those two function calls separately. But as it stands, second will not start until first 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”.

  • Related