修复线程池析构时所有线程没有退出

This commit is contained in:
Nanako 2025-01-06 19:26:50 +08:00
parent 48a6140deb
commit 9941d24190
3 changed files with 62 additions and 28 deletions

View File

@ -5,31 +5,46 @@
class thread_event { class thread_event {
public: public:
thread_event() = default;
explicit thread_event(bool manual_reset) : manual_reset(manual_reset) {}
void wait() { void wait() {
std::unique_lock lock(mutex); std::unique_lock lock(mutex);
cv.wait(lock, [this] { return signaled; }); cv.wait(lock, [this] { return signaled; });
signaled = false; if (!manual_reset) {
signaled = false;
}
} }
void wait(std::chrono::milliseconds timeout) { bool wait(std::chrono::milliseconds timeout) {
std::unique_lock lock(mutex); std::unique_lock lock(mutex);
cv.wait_for(lock, timeout, [this] { return signaled; }); const bool was_signaled = cv.wait_for(lock, timeout, [this] { return signaled; });
signaled = false; if (was_signaled && !manual_reset) {
signaled = false;
}
return was_signaled;
} }
void signal() { void signal() {
std::lock_guard lock(mutex); std::lock_guard lock(mutex);
signaled = true; signaled = true;
cv.notify_one(); if (manual_reset) {
cv.notify_all();
} else {
cv.notify_one();
}
} }
void broadcast_signal() { // 重置事件为无信号状态(仅手动复位事件使用)
std::lock_guard lock(mutex); void reset() {
signaled = true; if (manual_reset) {
cv.notify_all(); std::lock_guard lock(mutex);
signaled = false;
}
} }
private: private:
std::condition_variable cv; std::condition_variable cv;
std::mutex mutex; std::mutex mutex;
bool signaled = false; bool signaled = false;
bool manual_reset = false;
}; };

View File

@ -1,5 +1,7 @@
#include "thread_pool.h" #include "thread_pool.h"
#include <iostream>
thread_pool::thread_pool(const size_t num_threads) : stop(false) { thread_pool::thread_pool(const size_t num_threads) : stop(false) {
// 创建线程 // 创建线程
for (std::size_t i = 0; i < num_threads; ++i) { for (std::size_t i = 0; i < num_threads; ++i) {
@ -10,23 +12,35 @@ thread_pool::thread_pool(const size_t num_threads) : stop(false) {
thread_pool::~thread_pool() { thread_pool::~thread_pool() {
stop = true; stop = true;
// 唤醒所有线程 // 唤醒所有线程
task_available.broadcast_signal(); condition.notify_all();
for (auto& thread : threads) {
if (thread.joinable()) {
thread.join();
}
}
} }
void thread_pool::worker_thread() { void thread_pool::worker_thread() {
while (true) { while (true) {
// 如果线程池停止且任务队列为空,则退出 std::function<void()> task;
if (stop && tasks.empty()) { {
return; std::unique_lock lock(queue_mutex);
condition.wait(lock, [this] { return stop || !this->tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
} }
// 从任务队列中取出任务并执行 try {
if (const auto& task = tasks.pop()) { task();
task.value()(); } catch (const std::exception& e) {
continue; // 处理任务中的异常,避免线程池崩溃
std::cerr << "Task exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Task exception: unknown exception" << std::endl;
} }
// 如果任务队列为空,则等待任务
task_available.wait();
} }
} }

View File

@ -43,25 +43,30 @@ public:
auto submit(F&& in_func, Args&&... in_args) { auto submit(F&& in_func, Args&&... in_args) {
using return_type = std::invoke_result_t<F, Args...>; using return_type = std::invoke_result_t<F, Args...>;
auto bind_task = std::make_shared<std::packaged_task<return_type()>>( if (stop) { throw std::runtime_error("submit on stopped ThreadPool"); }
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(in_func), std::forward<Args>(in_args)...) std::bind(std::forward<F>(in_func), std::forward<Args>(in_args)...)
); );
auto res = bind_task->get_future(); auto res = task->get_future();
if (stop) { throw std::runtime_error("submit on stopped ThreadPool"); }
tasks.push([bind_task] { (*bind_task)(); }); {
task_available.signal(); std::lock_guard lock(queue_mutex);
tasks.push([task] { (*task)(); });
}
condition.notify_one();
return res; return res;
} }
private: private:
void worker_thread(); void worker_thread();
std::vector<std::jthread> threads; std::vector<std::thread> threads;
safe_queue<std::function<void()>> tasks; std::queue<std::function<void()>> tasks;
// 同步原语 // 同步原语
thread_event task_available; std::mutex queue_mutex;
std::condition_variable condition;
std::atomic_bool stop; std::atomic_bool stop;
}; };