Created
January 25, 2013 02:50
-
-
Save juehan/4631329 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <future> | |
#include <iostream> | |
#include <chrono> | |
//Speculative execution using std::future<> wait_for() | |
int quick_but_gestimation() | |
{ | |
for (int i=0; i < 2; i++) | |
{ | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::cout << "[quick func]: time elapsed : " << i << " second" << std::endl; | |
} | |
return 10; | |
} | |
int slow_but_accurate() | |
{ | |
for (int i=0; i < 6; i++) | |
{ | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::cout << "[slow func]: time elapsed : " << i << " second" << std::endl; | |
} | |
return 11; | |
} | |
std::future<int> f; | |
int bestResult() | |
{ | |
f = std::async(std::launch::async, slow_but_accurate); | |
int guestimation = quick_but_gestimation(); | |
std::future_status s = f.wait_for(std::chrono::seconds(3)); | |
if(s == std::future_status::ready) | |
return f.get(); | |
else | |
return guestimation; | |
} | |
int main() | |
{ | |
std::cout << "Best result: " << std::endl; | |
std::cout << bestResult() << std::endl; | |
} | |
/* | |
//output from g++ 4.7.2 | |
// When future object is declared and defined INSIDE bestResult() function | |
Best result: | |
[slow func]: time elapsed : 0 second[quick func]: time elapsed : | |
0 second | |
[quick func]: time elapsed : 1 second | |
[slow func]: time elapsed : 1 second | |
[slow func]: time elapsed : 2 second | |
[slow func]: time elapsed : 3 second | |
[slow func]: time elapsed : 4 second | |
[slow func]: time elapsed : 5 second | |
10 | |
Press ENTER to continue... | |
// When future object is declared and defined OUTSIDE bestResult() function | |
Best result: | |
[slow func]: time elapsed : [quick func]: time elapsed : 0 second | |
0 second | |
[slow func]: time elapsed : 1 second | |
[quick func]: time elapsed : 1 second | |
[slow func]: time elapsed : 2 second | |
[slow func]: time elapsed : 3 second | |
10 | |
[slow func]: time elapsed : 4 second | |
[slow func]: time elapsed : 5 second | |
Press ENTER to continue... | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GCC4.7
VS2012