TERMINATE CALLED RECURSIVELY
对应中文:终止递归调用。
错误原因
未知
发生错误的代码
代码修改前后只有构造函数初始化列表中有无
tPool(std::make_shared<pool>()).若无,运行程序则会报错terminate called after throwing an instance of ... terminate called recursively,terminate called recursively.
-
线程池:修改后
class threadPool {
public:
explicit threadPool(size_t thread_count = 8) : tPool(std::make_shared<pool>()) {
assert(thread_count > 0);
for (size_t i = 0; i < thread_count; ++i) {
std::thread([pool = tPool] {
std::unique_lock<std::mutex> locker(pool->m_mutex);
while (true) {
if (!pool->task_q.empty()) {
auto task = std::move(pool->task_q.front());
pool->task_q.pop();
locker.unlock();
task();
locker.lock();
}
else if(pool->shutdown)
break;
else
pool->m_cond.wait(locker);
}
}).detach();
}
}
threadPool() = default;
threadPool(threadPool&&) = default;
~threadPool() {
if (static_cast<bool>(tPool)) {
{
std::unique_lock<std::mutex> locker(tPool->m_mutex);
tPool->shutdown = true;
}
tPool->m_cond.notify_all();
}
}
template<class F>
void add_task(F &&task) {
{
std::unique_lock<std::mutex> locker(tPool->m_mutex);
tPool->task_q.emplace(std::forward<F>(task));
}
tPool->m_cond.notify_one();
}
private:
struct pool {
std::mutex m_mutex;
std::condition_variable m_cond;
bool shutdown;
std::queue<std::function<void()>> task_q;
};
std::shared_ptr<pool> tPool;
};
-
线程池:修改前
class threadPool {
public:
explicit threadPool(size_t thread_count = 8){
assert(thread_count > 0);
for (size_t i = 0; i < thread_count; ++i) {
std::thread([pool = tPool] {
std::unique_lock<std::mutex> locker(pool->m_mutex);
while (true) {
if (!pool->task_q.empty()) {
auto task = std::move(pool->task_q.front());
pool->task_q.pop();
locker.unlock();
task();
locker.lock();
}
else if(pool->shutdown)
break;
else
pool->m_cond.wait(locker);
}
}).detach();
}
}
};
参考链接

浙公网安备 33010602011771号