没有活动异常的 C 终止调用

新手上路,请多包涵

我在线程中遇到 C++ 错误:

 terminate called without an active exception
Aborted

这是代码:

 #include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

template<typename TYPE>
class blocking_stream
{
public:
    blocking_stream(size_t max_buffer_size_)
        :   max_buffer_size(max_buffer_size_)
    {
    }

    //PUSH data into the buffer
    blocking_stream &operator<<(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.size()>=max_buffer_size)
            stop_if_full.wait(mtx_lock);

        buffer.push(std::move(other));

        mtx_lock.unlock();
        stop_if_empty.notify_one();
        return *this;
    }
    //POP data out of the buffer
    blocking_stream &operator>>(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.empty())
            stop_if_empty.wait(mtx_lock);

        other.swap(buffer.front());
        buffer.pop();

        mtx_lock.unlock();
        stop_if_full.notify_one();
        return *this;
    }

private:
    size_t max_buffer_size;
    std::queue<TYPE> buffer;
    std::mutex mtx;
    std::condition_variable stop_if_empty,
                            stop_if_full;
    bool eof;
};

我围绕这个例子建模了我的代码: http ://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

我做错了什么,我该如何解决这个错误?

原文由 111111 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 818
2 个回答

当线程对象超出范围并处于可连接状态时,程序将终止。对于可连接线程的析构函数,标准委员会有另外两个选择。它可以悄悄地加入——但如果线程被卡住,加入可能永远不会返回。或者它可以分离线程(分离的线程不可连接)。然而,分离的线程非常棘手,因为它们可能会一直存活到程序结束并弄乱资源的释放。因此,如果您不想终止程序,请确保加入(或分离)每个线程。

原文由 Bartosz Milewski 发布,翻译遵循 CC BY-SA 3.0 许可协议

首先定义一个线程。如果在调用线程析构函数之前从未调用 join() 或 detach(),程序将中止。

如下,调用线程析构函数而不首先调用 join(等待它完成)或 detach 保证立即调用 std::terminate 并结束程序。

在其析构函数中隐式分离或加入 joinable() 线程可能导致仅在引发异常时遇到难以调试的正确性(分离)或性能(加入)错误。因此,程序员必须确保在线程仍可连接时永远不会执行析构函数。

原文由 Li Yingjun 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题