Created
September 3, 2023 10:20
-
-
Save jemand2001/c8eca186ccac692f8facc56015fdbc06 to your computer and use it in GitHub Desktop.
maybe a correct threadpool implementation in c++
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 <algorithm> | |
| #include <condition_variable> | |
| #include <functional> | |
| #include <mutex> | |
| #include <queue> | |
| #include <thread> | |
| #include <vector> | |
| struct threadpool { | |
| std::vector<std::jthread> threads; | |
| std::queue<std::function<void()>> callbacks; | |
| std::mutex mut; | |
| std::atomic_bool running; | |
| std::condition_variable cond; | |
| threadpool(size_t count = 4) | |
| : threads{count, std::jthread{[this](std::stop_token token) { | |
| worker(token); | |
| }}} {} | |
| void worker(std::stop_token token) { | |
| while (true) { | |
| if (token.stop_requested()) | |
| break; | |
| std::function<void()> f; | |
| { | |
| std::unique_lock lock{mut}; | |
| cond.wait(lock, [this]() { return callbacks.size() > 0; }); | |
| if (!running) | |
| break; | |
| f = callbacks.front(); | |
| callbacks.pop(); | |
| } | |
| f(); | |
| } | |
| } | |
| template <std::invocable Func> | |
| void add(Func &&f) { | |
| std::lock_guard lock{mut}; | |
| callbacks.emplace(std::forward<Func>(f)); | |
| cond.notify_one(); | |
| } | |
| ~threadpool() { | |
| { | |
| std::lock_guard lock{mut}; | |
| running = false; | |
| cond.notify_all(); | |
| } | |
| for (auto &t : threads) { | |
| t.request_stop(); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment