代码如下
#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; i++) {
if (_work_t

这篇博客探讨了C++11线程池实现中遇到的问题,包括线程池析构时的任务执行效率、异常处理机制的缺失、工作线程异常退出的处理以及模板函数的重载和std::future的限制。提出了改进方案,如在析构前处理所有任务、添加异常捕获、改进join机制以及优化emplace函数。最后,作者感叹C++的复杂性,指出还有很长的路要走。
最低0.47元/天 解锁文章
1618

被折叠的 条评论
为什么被折叠?



