Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cin.putback() and "wake up" it

I have threads in my program and I want to put character into stream and read it in another thread, but after std::cin.putback() I need to write something from keyboard to "wake up" std::cin in function main. Can I do something to read automatically?

like image 866
vesper Avatar asked May 30 '26 08:05

vesper


1 Answers

That's not how streams work. The std::cin reads data that come from outside your program to standard input and the putback only allows keeping a character that you actually just read back to the buffer for re-parsing next time you invoke operator>> (or get or getline or other read method).

If you want to communicate between threads, you should use a message queue from some threading library, e.g. Boost provides a decent portable one.

It is not possible to use streams, at least those provided by standard library, because stringstream is not thread-safe and fistream/fostream can't be created from raw file handle, so you can't combine them with POSIX pipe function. It would be possible to wrap a message queue in a stream (and boost gives you enough tools to do it), but the raw message queue API will probably be suitable.

like image 111
Jan Hudec Avatar answered Jun 01 '26 23:06

Jan Hudec