【发布时间】:2019-10-05 21:48:40
【问题描述】:
我正在寻找一种使用<iostream> 语义在线程之间创建通信流的简单方法。我正在寻找类似以下的内容:
#include <iostream>
#include <thread>
void thread1(std::istream from_main, std::ostream to_main) {
std::string s;
from_main >> s;
to_main << "Received:" << s << std::endl;
}
int main() {
std::istream from_thread;
std::ostream to_thread;
std::thread t(thread1, to_thread, from_thread);
to_thread << "Hi-Thread\n";
std::string s;
from_thread >> s; // Received:Hi-Thread
t.join();
}
有没有不使用pipe、创建文件描述符和用系统调用填充代码的简单方法?
【问题讨论】:
-
我很好奇您为什么需要管道、fds 和系统调用来执行此操作?一切都在同一个进程中,所以你可以有一个消息队列和一个锁,对吧?这里的用例是什么?
-
@ggorlen 是的,但我想念整个
std::stream语义,这非常好。 -
你的队列可以覆盖
<<和>>运算符。 -
@ggorlen 我当然可以,但这会给我带来各种错误的可能性。如果没有更标准的解决方案,我会感到非常惊讶。
-
似乎定义一个具有必要行为的
std::streambuf的子类相当简单。你可以构造一个 istream 和 ostream 来引用它。
标签: c++ multithreading c++11