代码之家  ›  专栏  ›  技术社区  ›  Kostas

在没有系统调用(管道)的线程之间使用std::istream和std::ostream

  •  0
  • Kostas  · 技术社区  · 5 年前

    我正在寻找一个简单的方法来创建线程之间的通信流 <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 ,创建文件描述符并用系统调用填充代码?

    0 回复  |  直到 5 年前
        1
  •  2
  •   John Zwinck    5 年前

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

    保持简单。 SPSC queue