Home > Blockchain >  Forwarding a function to std::thread via a lambda expression
Forwarding a function to std::thread via a lambda expression

Time:10-30

I'm working through the notes here to understand an example async function implementation.

Attempting to compile the below code

#include <future>
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>
#include <type_traits>


int f(int x) {
    auto start = std::chrono::system_clock::now();
    std::time_t start_time = std::chrono::system_clock::to_time_t(start);
    std::cout << "returning " << x << " at " << std::ctime(&start_time) << std::endl;
    return x;
}


template<typename Function, typename... Args>
auto async(Function&& function, Args&&... args) {

    std::promise<typename std::result_of<Function(Args...)>::type> outer_promise;
    auto future = outer_promise.get_future();
    auto lambda = [function, promise = std::move(outer_promise)](Args&&... args) mutable {
        try {
            promise.set_value(function(args...));
        } catch (...) {
            promise.set_exception(std::current_exception());
        }
    };

    std::thread t0(std::move(lambda), std::forward<Args>(args)...);
    t0.detach();
    return future;
}

int main() {

    auto result1 = async(f, 1); 
    auto result2 = async(f, 2); 

}

I get the following compiler errors, which I'm struggling to understand.

I'd like some guidance on why this function arg is not declared correctly according to the compiler.

In instantiation of 'async(Function&&, Args&& ...)::<lambda(Args&& ...)> mutable [with Function = int (&)(int); Args = {int}]':
22:61:   required from 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>'
28:3:   required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27:   required from here
22:88: error: variable 'function' has function type
22:88: error: variable 'function' has function type
 In instantiation of 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>':
28:3:   required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27:   required from here
22:18: error: field 'async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>::<function capture>' invalidly declared function type

CodePudding user response:

To get result type of result_of you have to access type:

std::promise< typename std::result_of<Function(Args...)>::type > outer_promise;
  • Related