samedi 5 octobre 2019

Use `std::istream` and `std::ostream` between threads without system calls (pipe)

I am looking for a simple way to create a stream of communication between threads using <iostream> semantics. I was looking for something like the following:

#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();
}

Is there a simple way of achieving this without using pipe, creating file descriptors and filling up the code with system calls?

Aucun commentaire:

Enregistrer un commentaire