Making C++ function awaitable

There’s nothing in that function to make it asynchronous. It just runs a long while loop and then returns an AsyncFuture that is not marked “done” (so Python will spend forever waiting for it).

Also, you should really use PT(AsyncFuture) and allocate a future on the heap with new.

Your C++ method should actually be creating a task (which inherits AsyncFuture, so you can just return the task) or a thread (from which you can call future->set_result()).

Here is an example using C++11 threads:

  PT(AsyncFuture) test_me() {
    PT(AsyncFuture) ret_me = new AsyncFuture;

    std::thread t([=](){
      // do something that runs in the background

      // let the future know that it's done
      ret_me->set_result(nullptr);
    });
    t.detach();

    return ret_me;
  }

If you are comfortable using C++20, you can actually use C++20 coroutines with the Panda3D task manager. You need some glue code with that, but that would allow you to write async code as easily as with Python:

1 Like