///////////////////////////////////////////////////////////////////////////// // CustomAsync.cpp - how std::asynch works (Fawcett approximation thereof) // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2018 // ///////////////////////////////////////////////////////////////////////////// #include #include #include #include #include /*----< custom approximation to std::async >-------------------------*/ template std::future asynchCustom(Callable co, Arg arg) { std::promise prm; std::future fut(prm.get_future()); /* Note: must capture co by value, as original co may go out of scope before thread calls it */ auto lambda = [co](Arg arg, std::promise p) { std::cout << "\n starting thread's work"; Ret ret = co(arg); std::cout << "\n thread's work complete"; p.set_value(ret); }; /* Need to move ownership of promise to lambda */ std::thread t(lambda, arg, std::move(prm)); // running callable on child thread t.detach(); // detaching so no assert at program end return fut; } /*----< a callable used to test asynchCustom >-----------------------*/ std::string announce(const std::string& msg) { std::cout << "\n announce function is running asynchronously"; std::this_thread::sleep_for(std::chrono::milliseconds(2000)); return msg; } using R = std::string; using A = const std::string&; using C = R(*)(A); int main() { std::cout << "\n Demonstrating asynchCustom"; std::cout << "\n ============================"; C callable = announce; A arg = "That's all folks!"; std::future r = asynchCustom(callable, arg); std::cout << "\n returned from asynchCustom(...)"; ///////////////////////////////////////////////////////////////////// // this works too: // std::future r = asynchCustom(announce, "That's all folks!"); std::string result = r.get(); std::cout << "\n " << "asynchCustom returned \"" << result.c_str() << "\""; std::cout << "\n"; std::cout << "\n repeating with a lamda callable"; A arg2 = "Here's more folks!"; std::future r2 = asynchCustom( [=](A arg2) { std::cout << "\n running lambda asynchronously"; return arg2; }, arg2 ); result = r2.get(); std::cout << "\n " << "asynchCustom returned \"" << result.c_str() << "\""; std::cout << "\n\n"; return 0; }