Skip to content

Instantly share code, notes, and snippets.

@dudoslav
Created May 20, 2020 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudoslav/ad93c5c242fd53356ea9c0a13fa9354d to your computer and use it in GitHub Desktop.
Save dudoslav/ad93c5c242fd53356ea9c0a13fa9354d to your computer and use it in GitHub Desktop.
Async Pool
template<typename Fun, typename... Args>
class Pool {
std::vector<std::thread> _workers;
Queue<std::tuple<Args...>> _jobs;
std::mutex _mutex;
std::condition_variable _cv;
std::atomic<bool> _finished = false;
public:
template<typename F>
Pool(F&& fun, std::size_t threads = 4) {
auto worker = [&, fun](){
auto ul = std::unique_lock{_mutex};
while (true) {
if (_jobs.empty())
_cv.wait(ul, [&](){ return !_jobs.empty() || _finished; });
if (_finished) break;
std::apply(fun, _jobs.pop());
}
};
for (std::size_t i = 0; i < threads; ++i)
_workers.emplace_back(worker);
}
~Pool() {
_finished = true;
_cv.notify_all();
for (auto& worker: _workers)
worker.join();
}
void run(Args... args) {
_jobs.push(std::forward<Args>(args)...);
_cv.notify_one();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment