0

我正在寻找一种使用<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、创建文件描述符和用系统调用填充代码的情况下实现这一点?

4

1 回答 1

2

看起来您需要的是一个单生产者、单消费者 (SPSC) 队列,可能是无锁的。我会从这个开始,如果你觉得非常需要构建语法糖来制作operator<<mean spsc_queue::push_back,稍后再添加。不要从 C++operator <<语法的角度出发,然后认为“哦,这意味着 std::ostream”,然后会导致“让我们自定义streambuf.”。

把事情简单化。 SPSC 队列

于 2019-10-06T02:01:00.717 回答