【发布时间】:2011-11-14 22:56:09
【问题描述】:
我在线程处理方面遇到 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
我做错了什么以及如何修复错误?
【问题讨论】:
-
你是在
joining 主程序中的所有线程吗? -
向我们展示其余的代码。
-
@Kerrek 啊哈这解决了问题,我不知道为什么虽然我确定主线程没有在工人完成之前终止。我的锁定算法也看起来正确吗?
-
请重现问题的可编译代码。
-
在这种情况下,运行时似乎可以发出更好的诊断信息?
标签: c++ multithreading deadlock c++11