std::cin.putback() 和“唤醒”它
我的程序中有线程,我想将字符放入流中并在另一个线程中读取它,但是在 std::cin.putback() 之后,我需要从键盘写一些东西来“唤醒”函数 main 中的 std::cin 。我可以做一些自动阅读的事情吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
流不是这样工作的。
std::cin
将来自程序外部的数据读取到标准输入,而putback
只允许保留您实际刚刚读取的字符返回到缓冲区以便下次调用operator>>(或get
或getline
或其他读取方法)时重新解析。如果你想在线程之间进行通信,你应该使用一些线程库中的消息队列,例如 Boost 提供了一个不错的可移植性一。
不可能使用流,至少是标准库提供的流,因为
stringstream
不是线程安全的,而fistream
/fostream
可以'不是从原始文件句柄创建的,因此不能将它们与 POSIXpipe
函数结合起来。可以将消息队列包装在流中(boost 为您提供了足够的工具来做到这一点),但原始消息队列 API 可能会合适。That's not how streams work. The
std::cin
reads data that come from outside your program to standard input and theputback
only allows keeping a character that you actually just read back to the buffer for re-parsing next time you invokeoperator>>
(orget
orgetline
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 andfistream
/fostream
can't be created from raw file handle, so you can't combine them with POSIXpipe
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.