Callback Example inspired from proposed Boost.Async
/////////////////////////////////////////////////////////////////////////////// | |
// Copyright (c) 2016 Thomas Heller | |
// | |
// Distributed under the Boost Software License, Version 1.0. (See accompanying | |
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) | |
/////////////////////////////////////////////////////////////////////////////// | |
#include <hpx/hpx.hpp> | |
#include <hpx/hpx_main.hpp> | |
#include <hpx/include/threads.hpp> | |
#include <iostream> | |
struct manager | |
{ | |
manager() | |
: executor(1) | |
{} | |
hpx::future<void> second() | |
{ | |
// return the future once we are done. | |
return | |
// Start the task in the correct thread world | |
hpx::async( | |
executor, | |
[]() | |
{ | |
std::cout << "Executing second long task...\n"; | |
hpx::this_thread::sleep_for(std::chrono::milliseconds(1000)); | |
} | |
// Once it is done, execute the continuation/callback in the | |
// same thread world. Instead of the executor, we could have used | |
// hpx::launch::sync to get the same effect | |
).then(executor, | |
[](hpx::future<void> f) | |
{ | |
std::cout << "shutting down after second task is completed\n"; | |
} | |
); | |
} | |
hpx::future<void> start() | |
{ | |
// return the future once we are done. | |
return | |
// Start the task in the correct thread world | |
hpx::async( | |
executor, | |
[]() | |
{ | |
std::cout << "Executing long task...\n"; | |
hpx::this_thread::sleep_for(std::chrono::milliseconds(1000)); | |
} | |
// Once it is done, execute the continuation/callback in the | |
// same thread world. Instead of the executor, we could have used | |
// hpx::launch::sync to get the same effect | |
).then(executor, | |
[this](hpx::future<void> f) | |
{ | |
if (needs_second_task) | |
{ | |
return second(); | |
} | |
else | |
{ | |
std::cout << "shutdown after first task\n"; | |
return hpx::make_ready_future(); | |
} | |
} | |
); | |
} | |
void cancel() | |
{ | |
// fire&forget, cancel the manager in the corresponding thread world | |
hpx::apply(executor, [this](){ needs_second_task = false; }); | |
} | |
// our thread world... | |
hpx::threads::executors::local_queue_executor executor; | |
bool needs_second_task = true; | |
}; | |
int main() | |
{ | |
std::cout << "example callback\n"; | |
manager man; | |
auto fu = man.start(); | |
// we changed our mind, cancel the manager right away | |
man.cancel(); | |
// wait for shutdown | |
fu.get(); | |
std::cout << "end example callback\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment