线程安全队列出现分段错误
Thread safe queue gives segmentation fault
我正在编写一个线程安全队列来添加字符串流对象。我以为发生了分段错误,因为stringstream ss
添加到队列时被破坏了,但正如您所看到的,我正在移动它std::move()
#include <iostream>
#include <mutex>
#include <sstream>
#include <queue>
#include <condition_variable>
template <typename T>
class ThreadSafeQueue
{
public:
/*
Returns the front element and removes it from the collection
No exception is ever returned as we garanty that the deque is not empty
before trying to return data.
This is useful in our while loop renderer, because it just waits if there
are no members to be popped.
*/
T pop(void) noexcept
{
std::unique_lock<std::mutex> lock{_mutex};
while (_collection.empty())
{
_condNewData.wait(lock);
}
auto elem = std::move(_collection.front());
_collection.pop();
return elem;
}
template <typename... Args>
void emplace(Args &&... args)
{
addDataProtected([&] {
_collection.emplace(std::forward<Args>(args)...);
});
}
private:
/*
Locks the thread and do something with the deque.
Then unique_lock goes away and unlocks the thread
*/
template <class F>
decltype(auto) lockAndDo(F &&fct)
{
std::unique_lock<std::mutex> lock{_mutex};
return fct();
}
template <class F>
void addDataProtected(F &&fct)
{
lockAndDo(std::forward<F>(fct));
_condNewData.notify_one();
}
private:
std::queue<T> _collection; // Concrete, not thread safe, storage.
std::mutex _mutex; // Mutex protecting the concrete storage
std::condition_variable _condNewData; // Condition used to notify that new data are available.
};
int main()
{
std::unique_ptr<ThreadSafeQueue<std::stringstream>> logMessages;
std::stringstream ss;
ss << "hello";
logMessages->emplace(std::move(ss));
return 0;
}
std::unique_ptr<ThreadSafeQueue<std::stringstream>> logMessages;
您从未为此变量分配内存。 它不指向ThreadSafeQueue<>
对象
或
auto logMessages = std::make_unique<ThreadSafeQueue<std::stringstream>>();
相反?
或者只是按照评论中的建议制作普通对象。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?