Search code examples
c++asynchronouslambdaasync-awaitrpc

How to create async/await code in C++?


I'm using remote RPC of my network service and I don't want to create any delegates in my code with binding an other things. I want to wrote pseudo-asynchroused code. Something like this:

 await (MyServer->RemoteMethod(parameter_1, parameter_2), 
      [=] (int32 return_value_1, int32 return_value_2) {
           UE_LOG(MyLog, Log, TEXT("RemoteMethod called with result %i %i"), return_value_1, return_value_2);
      });

I'm not too strong in functional programming of latest C++ versions. But I know there is things like std::function. Can this help me?

Also I need that code must be cross-platform.


Solution

  • What you're describing is not async-await, with that, you would be able to write:

    std::pair<int32, int32> return_values = await MyServer->RemoteMethod(parameter_1, parameter_2);
    UE_LOG(MyLog, Log, TEXT("RemoteMethod called with result %i %i"), return_values.first, return_values.second);
    

    I believe this feature is planned to be in some future version of C++.

    What you're describing is a continuation and you can use boost::future for that:

    boost::future<std::pair<int32, int32>> return_values_future = MyServer->RemoteMethod(parameter_1, parameter_2);
    return_values_future.then([=](boost::future<std::pair<int32, int32>> fut) {
        UE_LOG(MyLog, Log, TEXT("RemoteMethod called with result %i %i"), fut.get().first, fut.get().second);
    });