gpt4 book ai didi

c++ - 线程没有被分离

转载 作者:太空狗 更新时间:2023-10-29 20:39:31 26 4
gpt4 key购买 nike

我正在尝试制作一个线程池。我有一个 std::unordered_map,它将线程 ID 映射到 std::thread(workers)。线程 ID 是等待任务被插入线程池的线程的 ID(waiters)。任务由 std::stack (tasks) 表示。一旦任务被插入池中,任务就会从堆栈中弹出,并作为映射的“值”部分成为线程函数。

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

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;
}

我什至不确定这是最好的方法,这是我第一次做。 Here is a demo.

最佳答案

在你的池析构函数中,你正在调用 pop before 分离线程,有效地破坏一个可连接的线程:标准保证这将调用 std::terminate

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

while (!waiters.empty())
{
auto& t = waiters.front();

if (t.joinable())
t.detach();

waiters.pop();
}

关于c++ - 线程没有被分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27683034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com