线程未分离

Threads are not being detached

本文关键字:未分离 线程      更新时间:2023-10-16

我正在尝试创建一个线程池。我有一个std::unordered_map将线程 ID 映射到 std::thread s ( workers )。线程 ID 是等待将任务推送到线程池 (waiters ) 的线程的 ID。任务由std::stacktasks ) 表示。一旦任务被推入池中,该任务就会从堆栈中弹出,并作为映射的"值"部分变成线程函数。

在析构函数中,我尝试分离所有仍在运行的线程。但我仍然得到以下异常:

terminate called without an active exception
bash: line 7: 16881 Aborted                 (core dumped) ./a.out

这意味着线程未分离,程序终止。但是我的析构函数会穿过元素并分离它们(我相信)。为什么会发生这种情况,我该如何解决?

#include <queue>
#include <stack>
#include <mutex>
#include <thread>
#include <algorithm>
#include <functional>
#include <type_traits>
#include <unordered_map>
#include <condition_variable>
template <class F>
class thread_pool
{
    static_assert(std::is_function<F>::value, "F must have function type");
public:
    thread_pool();
    ~thread_pool();
    template <class Task>
    void push(Task&&);
private:
    std::unordered_map<std::thread::id, std::thread> workers;
    std::queue<std::thread> waiters;
    std::stack<std::function<F>> tasks;
    static std::size_t max;
private:
    std::condition_variable m_cond;
    std::mutex m;
private:
    void wait_for_tasks();
};
template <class F>
std::size_t thread_pool<F>::max(10);
template <class F>
thread_pool<F>::thread_pool()
{
    std::lock_guard<std::mutex> lock(m);
    for (std::size_t i = 0; i < max; ++i)
        waiters.emplace(&thread_pool<F>::wait_for_tasks, this);
}
template <class F>
void thread_pool<F>::wait_for_tasks()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(m);
        m_cond.wait(lock, [this] { return !tasks.empty(); });
        auto f = tasks.top();
        tasks.pop();
        auto& th = workers[std::this_thread::get_id()];
        if (th.get_id() == std::thread::id())
            th = std::thread(f);
    }
}
template <class F>
template <class Task>
void thread_pool<F>::push(Task&& t)
{
    {
        std::lock_guard<std::mutex> lock(m);
        tasks.emplace(std::forward<Task>(t));
    }
    m_cond.notify_all();
}
template <class F>
thread_pool<F>::~thread_pool()
{
    std::for_each(workers.begin(), workers.end(), [] (std::pair<std::thread::id const, std::thread>& p)
    {
        if (p.second.joinable())
            p.second.detach();
    });
    while (!waiters.empty())
    {
        auto& t = waiters.front();
        waiters.pop();
        if (t.joinable())
            t.detach();
    }
}
int main()
{
    thread_pool<void ()> pool;
}

我什至不确定这是最好的方法,这是我第一次做一个。这是一个演示。

在池析构函数中,您在分离线程之前调用pop,有效地破坏了可连接的线程:标准保证这将调用std::terminate

首先分离线程,然后将其从队列中弹出:

while (!waiters.empty())
{
    auto& t = waiters.front();
    if (t.joinable())
        t.detach();
    waiters.pop();
}