-
-
Save anonymous/59178dd70424666f492d to your computer and use it in GitHub Desktop.
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
class SimpleThreadPool { | |
public: | |
SimpleThreadPool(int max_threads): | |
max_threads_(max_threads) { | |
for (int idx = 0; idx < max_threads_; idx++) { | |
std::thread thread([this]() { | |
this->ThreadRun(); | |
}); | |
threads_.push_back(std::move(thread)); | |
} | |
} | |
void ThreadRun() { | |
while(true) { | |
std::function<void(void)> task_; | |
{ | |
std::unique_lock<std::mutex> guard_(tasks_lock_); | |
while (tasks_.empty()) { | |
tasks_condvar_.wait(guard_); | |
} | |
task_ = tasks_.back(); | |
tasks_.pop_back(); | |
} | |
task_(); | |
} | |
} | |
template <typename T> | |
std::future<T> Submit(std::function<T()> task_func) { | |
std::packaged_task<T()> task; | |
std::future<T> task_future = task.get_future(); | |
{ | |
std::unique_lock<std::mutex> guard_(tasks_lock_); | |
std::function<std::packaged_task<T()>> unbound = [](std::packaged_task<T()> bound_task)->void { | |
bound_task(); | |
}; | |
std::function<void(void)> bound_func = std::bind(unbound, std::move(task)); | |
tasks_.push_front(bound_func); | |
} | |
tasks_condvar_.notify_one(); | |
return task_future; | |
} | |
private: | |
int max_threads_; | |
std::mutex tasks_lock_; | |
std::condition_variable tasks_condvar_;; | |
std::deque<std::function<void(void)>> tasks_; | |
std::vector<std::thread> threads_; | |
}; | |
int main() { | |
SimpleThreadPool tp(5); | |
auto res = tp.Submit<int>([]()->int { | |
std::cout << "hello world" << std::endl; | |
return 10; | |
}); | |
try { | |
std::cout << "Got result " << res.get() << std::endl; | |
} catch (std::future_error& e) { | |
std::cerr << "ERROR: " << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment