Created
October 29, 2013 20:44
-
-
Save Fraser999/7222276 to your computer and use it in GitHub Desktop.
Shows results of `wait_for` on a deferred function.
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 <chrono> | |
#include <future> | |
#include <iostream> | |
#include <string> | |
#include <thread> | |
void DoStuff() { | |
std::cout << "Starting task.\n"; | |
std::this_thread::sleep_for(std::chrono::seconds(2)); | |
} | |
std::string WaitFor(std::future<void>& future) { | |
const std::chrono::seconds timeout(1); | |
auto start(std::chrono::steady_clock::now()); | |
auto result(future.wait_for(timeout)); | |
std::string status(result == std::future_status::ready ? "ready" : | |
result == std::future_status::timeout ? "timeout" : "deferred"); | |
std::string blocked(std::chrono::steady_clock::now() - start >= timeout ? | |
"blocked" : "not blocked"); | |
return std::string("status: ") + status + '\t' + blocked + '\n'; | |
} | |
int main() { | |
auto deferred_future(std::async(std::launch::deferred, DoStuff)); | |
std::string result("deferred_future - " + WaitFor(deferred_future)); | |
std::cout << result; | |
auto async_future(std::async(std::launch::async, DoStuff)); | |
result = "async_future - " + WaitFor(async_future); | |
std::cout << result; | |
std::promise<void> promise; | |
auto promise_future(promise.get_future()); | |
result = "promise_future - " + WaitFor(promise_future); | |
std::cout << result; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment