P
puzzlecracker
is it even possible or/and there is a better alternative to accept
input in a nonblocking manner?
input in a nonblocking manner?
You could try using 'peek' member function. You should get
'eof' if no input is available, I am guessing, but don't take
my word for it, RTFM and experiment.
is it even possible
or/and there is a better alternative to accept input
in a nonblocking manner?
I don't believe it is in an OS-independent way. I don't think C++ has a
notion of non-blocking I/O at all - a read failure is always simply
treated as an "error".
Maybe have a look at the Boost.Iostreams library:
http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html
and in particular section 3.6 (Asynchronous and Non-Blocking I/O). But I
get the impression it's not quite there yet.
I'm not sure what you mean here.
What are you actually trying to do? I can tell you how to put stdin into
non-blocking mode on a POSIX (e.g. Linux) terminal, if you're interested
(and also how to make it non line-buffered, which you probably want too
in that case).
puzzlecracker said:is it even possible or/and there is a better alternative to accept
input in a nonblocking manner?
If you want non-blocking I/O, you probably don't want iostreams, at
least not using standard streambufs. How would you differentiate a
"would block" condition from an end of file?
You can use non-blocking I/O, but you'd have to provide your own
streambuf object.
Sure, I am actually building apps on Linux, hence posix works. Can't use
boost. Please demonstrate it(please don't flame me for OT)
I won't, but someone else possibly will![]()
I'd avoid the problem altogether:
I'd simply create a cin reader thread whose job would be to read input
safely from a blocking cin. It could also be charged with validating
this input if desirable.
I'd put a thread safe FIFO communication mechanism between the two
threads (e.g. mutex protected std::queue) and the main process thread
would peek if there is a message on the queue for it, if so, read and
process it, if not, continue with its other tasks.
To me, that sounds simpler than trying to turn cin as non-blocking. plus
anyway, non-blocking cin would think that there is data to be read if
only one character was present in the buffer but you may wish to get
input as complete words (lines?) and not interrupt normal processing
until a complete word is available. This would be trivial to do with
the input thread model but much more difficult with a non-blocking cin
or stdin.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.