Skip to content

Instantly share code, notes, and snippets.

@geneotech
Last active September 15, 2017 20:06
Show Gist options
  • Save geneotech/5b0acb9487f22e3e0ef40f8c1d30b8cb to your computer and use it in GitHub Desktop.
Save geneotech/5b0acb9487f22e3e0ef40f8c1d30b8cb to your computer and use it in GitHub Desktop.
future considerations
// UPDATE: So, I've implemented a packaged_future template which makes it possible to use just a single variable:
// https://gist.github.com/geneotech/c9e8177b34dbace6b1fa23129977c9d1
// Original problem:
// UPDATE: Okay, so apparently, std::shared_future can get multiple times...
// But should I use std::shared_future even though just one thread queries it for value?
// Consider a main menu class which, on construction,
// is supposed to query a website for a news headline in order
// to render it later on top of the game's main menu.
// (which I already had before, just uglier).
// This sounds like a task for std::future, but I think using two member variables for this is ugly,
// and I don't see a way to use just a single variable
// Or maybe it is in fact good to use two variables?
// Or maybe we should make a packaged_future template helper which stores both and returns an std::optional?
// Helper template (recommended by SO folks)
template <class T>
bool is_ready(const std::future<T>& f) {
return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
class main_menu_setup {
std::future<void> latest_news_future;
std::wstring latest_news;
main_menu_setup(const main_menu_settings settings) {
query_latest_news(settings.latest_news_url);
// more ...
}
void query_latest_news(const std::string& url) {
latest_news_future = std::async(std::launc::async, [&]() {
auto html = augs::http_get_request(url);
// processing...
latest_news = to_wstring(html);
});
}
// these are meant to be called repeatedly later
void draw() const {
if (latest_news_future.valid() && is_ready(latest_news_future)) {
print(latest_news);
};
}
}
// Do you think there's a better way?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment