Last active
November 10, 2016 14:46
-
-
Save plasticbox/c221fdd4046225b274ee0e5d88505ab8 to your computer and use it in GitHub Desktop.
std::packaged_task
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 <iostream> | |
#include <thread> | |
#include <future> | |
#include <queue> | |
class ITask | |
{ | |
public: | |
virtual ~ITask() {}; | |
virtual void execute() = 0; | |
}; | |
template <typename T> | |
class Task : public ITask | |
{ | |
public: | |
std::packaged_task<T()> task_; | |
Task(std::function<T()> func) : task_(func) {} | |
void execute() { task_(); } | |
}; | |
template<typename Function, typename ...Args> | |
std::future<typename std::result_of<Function(Args...)>::type> pushTask(Function &&f, Args &&...args) { | |
auto task = std::make_unique<Task<typename std::result_of<Function(Args...)>::type>>(std::bind(f, args...)); | |
auto future = task->task_.get_future(); | |
task_queue.push(std::move(task)); | |
return future; | |
} | |
std::queue<std::unique_ptr<ITask>> task_queue; | |
std::atomic<bool> shutdown; | |
int taskfunction(int i) { | |
std::cout << "taskfunction thread num : " << std::this_thread::get_id() << ", arg : " << i << std::endl; | |
return i; | |
} | |
int main() | |
{ | |
std::cout << "main thread num : " << std::this_thread::get_id() << std::endl; | |
auto t = std::thread([]() { | |
for (;;) { | |
if (shutdown) { return; } | |
if (!task_queue.empty()) | |
{ | |
auto task = std::move(task_queue.front()); | |
task_queue.pop(); | |
if (task) | |
{ | |
task->execute(); | |
} | |
task.release(); | |
} | |
} | |
}); | |
auto result1 = pushTask(taskfunction, 12); | |
auto result2 = pushTask(taskfunction, 13); | |
auto result3 = pushTask(taskfunction, 14); | |
std::cout << "result : " << result1.get() << std::endl; | |
std::cout << "result : " << result2.get() << std::endl; | |
std::cout << "result : " << result3.get() << std::endl; | |
shutdown = true; | |
t.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment