Last active
August 18, 2019 00:28
-
-
Save AndrewRademacher/55010ecd6bf29f5abbaf25594bd01796 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <boost/asio.hpp> | |
#include <boost/asio/bind_executor.hpp> | |
#include <boost/asio/spawn.hpp> | |
#include <boost/bind.hpp> | |
#include <chrono> | |
#include <random> | |
#include <spdlog/spdlog.h> | |
#include <thread> | |
int32_t next_int() { | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::random_device r; | |
std::default_random_engine e(r()); | |
std::uniform_int_distribution dist(0, 1000000); | |
return dist(e); | |
} | |
struct next_int_op { | |
template <typename CompletionToken> | |
decltype(auto) operator()(CompletionToken&& token) const { | |
int32_t value = next_int(); | |
token({}, value); | |
} | |
}; | |
template <typename CompletionToken> | |
decltype(auto) async_next_int(CompletionToken&& token) { | |
return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, int32_t)>(next_int_op(), token); | |
} | |
void get_nums_yield(boost::asio::yield_context yield) { | |
spdlog::info("boost::asio::yield_context"); | |
int32_t num_1 = async_next_int(yield); | |
spdlog::info("Num 1: {}", num_1); | |
int32_t num_2 = async_next_int(yield); | |
spdlog::info("Num 2: {}", num_2); | |
} | |
boost::asio::awaitable<void> get_nums_await() { | |
spdlog::info("boost::asio::awaitable"); | |
int32_t num_1 = co_await async_next_int(boost::asio::use_awaitable); | |
spdlog::info("Num 1: {}", num_1); | |
int32_t num_2 = co_await async_next_int(boost::asio::use_awaitable); | |
spdlog::info("Num 2: {}", num_2); | |
} | |
int main() { | |
boost::asio::io_context ui_ioc; | |
boost::asio::spawn(ui_ioc, &get_nums_yield); | |
boost::asio::co_spawn(ui_ioc, &get_nums_await, boost::asio::detached); | |
ui_ioc.poll(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment