// Copyright (C) 2016 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_AsYNC_Hh_ #define DLIB_AsYNC_Hh_ // C++11 things don't work in old versions of visual studio #if !defined( _MSC_VER) || _MSC_VER >= 1900 #include "async_abstract.h" #include "thread_pool_extension.h" #include #include namespace dlib { // ---------------------------------------------------------------------------------------- namespace impl { template struct selector {}; template void call_prom_set_value( T& prom, U& fun, selector ) { prom.set_value(fun()); } template void call_prom_set_value( T& prom, U& fun, selector ) { fun(); prom.set_value(); } template struct result_of; #if (__cplusplus >= 201703L || \ (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)) && \ __cpp_lib_is_invocable >= 201703L template struct result_of : std::invoke_result {}; #else template struct result_of : std::result_of {}; #endif } // ---------------------------------------------------------------------------------------- thread_pool& default_thread_pool(); // ---------------------------------------------------------------------------------------- template < typename Function, typename ...Args > std::future::type> async( thread_pool& tp, Function&& f, Args&&... args ) { auto prom = std::make_shared::type>>(); std::future::type> ret = prom->get_future(); using bind_t = decltype(std::bind(std::forward(f), std::forward(args)...)); auto fun = std::make_shared(std::bind(std::forward(f), std::forward(args)...)); tp.add_task_by_value([fun, prom]() { try { impl::call_prom_set_value(*prom, *fun, impl::selector::type>()); } catch(...) { prom->set_exception(std::current_exception()); } }); return ret; } // ---------------------------------------------------------------------------------------- template < typename Function, typename ...Args > std::future::type> async( Function&& f, Args&&... args ) { return async(default_thread_pool(), std::forward(f), std::forward(args)...); } } // ---------------------------------------------------------------------------------------- #ifdef NO_MAKEFILE #include "async.cpp" #endif #endif #endif // DLIB_AsYNC_Hh_