Created
May 20, 2020 11:00
-
-
Save dudoslav/ad93c5c242fd53356ea9c0a13fa9354d to your computer and use it in GitHub Desktop.
Async Pool
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
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