Making C++ function awaitable

Hi all,

I’m playing around with coroutines and have hit a problem when it comes to using await with a custom c++ function. To demonstrate:
On the python side:

   async def mainAsyncTest(self):
       print("start count...")
       await instaTezt.test_me()
       print("end count!")

On the c++ side:

    AsyncFuture test_me()
        AsyncFuture ret_me;
        int bb=0;
            cout<<"lesser_than: "<<bb<<"\n";
        return ret_me;

This still interrupts the main loop and freezes the application. Prepending the keyword “BLOCKING” to the c++ function doesn’t fix things either. I’m terribly sorry if this is a simple question, but I am just getting started with this particular feature after all.

Any help is appreciated, thanks.

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

    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

Thank you so much! Not only is this example crystal clear, it fits my use-case perfectly. Thanks again!

1 Like