代码如下
#include <iostream>
#include <queue>
#include <functional>
#include <memory>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <future>
constexpr const size_t DEFAULT_CAPACITY = 1;
class thread_pool {
typedef std::function<void()> task;
std::mutex _m;
std::condition_variable _cv;
std::atomic<bool> _stop;
std::vector<std::thread> _work_threads;
std::queue<task> _vector;
public:
explicit thread_pool(size_t cap = DEFAULT_CAPACITY) : _vector{}, _work_threads{}, _m{}, _cv{}, _stop{false} {
for (size_t i = 0; i < cap; i++) {
_work_threads.emplace_back(&thread_pool::run, this);
}
}
thread_pool(const thread_pool &) = delete;
~thread_pool() {
_stop = true;
_cv.notify_all();
for (size_t i = 0; i < DEFAULT_CAPACITY