【发布时间】:2020-09-08 08:40:34
【问题描述】:
我正在使用std::iostreams 在线程之间发送流数据,但难以提取数据,这是一个人为的示例:
#include <sstream>
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
using namespace std::chrono_literals;
int main()
{
auto stream = std::stringstream{};
auto stop = std::atomic_bool{false};
auto mtx = std::mutex{};
auto thread = std::thread{[&]() {
while(!stop) {
auto lock = std::lock_guard{mtx};
if (stream.peek() != decltype(stream)::traits_type::eof()) {
auto str = std::string{};
stream >> str;
std::cout << str;
}
}
}};
{
// Make sure thread is running before sending data
std::this_thread::sleep_for(100ms);
{
auto lock = std::lock_guard{mtx};
stream << "hello" << std::endl;
}
// Give the thread a chance to receive it
std::this_thread::sleep_for(100ms);
}
stop = true;
thread.join();
return EXIT_SUCCESS;
}
Running it,没有输出 - 调试显示stream.peek() 总是 EOF。我一定是做错了什么,但我看不到!
【问题讨论】:
标签: c++ multithreading iostream