gpt4 book ai didi

c++ - 线程安全队列给出段错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:29:46 25 4
gpt4 key购买 nike

我正在编写一个线程安全队列来添加字符串流对象。我认为发生段错误是因为 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>>();

代替?

或者按照评论中的建议制作普通对象。

关于c++ - 线程安全队列给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618127/

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