Created
March 2, 2019 04:52
-
-
Save chrischoy/81493d2a2294e252cd0d8ca35f575b70 to your computer and use it in GitHub Desktop.
task.cpp
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 <cmath> | |
#include <functional> | |
#include <future> | |
#include <iostream> | |
#include <thread> | |
// unique function to avoid disambiguating the std::pow overload set | |
int f(int x, int y) { return std::pow(x, y); } | |
class Functor { | |
public: | |
int operator()(int x, int y) const { return x + y; } | |
}; | |
void task_lambda() { | |
std::packaged_task<int(int, int)> task( | |
[](int a, int b) { return std::pow(a, b); }); | |
std::future<int> result = task.get_future(); | |
task(2, 9); | |
std::cout << "task_lambda:\t" << result.get() << '\n'; | |
} | |
void task_bind() { | |
std::packaged_task<int()> task(std::bind(f, 2, 11)); | |
std::future<int> result = task.get_future(); | |
task(); | |
std::cout << "task_bind:\t" << result.get() << '\n'; | |
} | |
void task_thread() { | |
std::packaged_task<int(int, int)> task(f); | |
std::future<int> result = task.get_future(); | |
std::thread task_td(std::move(task), 2, 10); | |
task_td.join(); | |
std::cout << "task_thread:\t" << result.get() << '\n'; | |
} | |
void task_functor() { | |
Functor func; | |
auto bind = std::bind(&Functor::operator(), &func, 2, 11); | |
std::packaged_task<int()> task(bind); | |
std::future<int> result = task.get_future(); | |
task(); | |
std::cout << "task_functor:\t" << result.get() << '\n'; | |
} | |
int main() { | |
task_lambda(); | |
task_bind(); | |
task_thread(); | |
task_functor(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment