Last active
December 11, 2015 02:09
-
-
Save juehan/4528873 to your computer and use it in GitHub Desktop.
C++11 high level thread interface using async() and future<>
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> | |
void print2Screen(char c) | |
{ | |
for(int i = 0; i < 50; i++) | |
{ | |
std::cout.put(c).flush(); | |
_sleep(100); //sleep 100 millisec | |
} | |
} | |
void func1() | |
{ | |
return print2Screen('+'); | |
} | |
void func2() | |
{ | |
return print2Screen('-'); | |
} | |
int main() | |
{ | |
std::cout << "Start func1() in background " | |
<< "while func2() in foreground" << std::endl; | |
//call func1 asynchronously and store the result to future object | |
std::future<void> task1(std::async(func1)); | |
func2(); //Call func2() synchronously (here and now) | |
//To force execution of func1(), we call get() for the returned future. | |
task1.get(); | |
std::cout << "\n\nDone with C++11 high level threading model" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment