is it possible to force a thread to return from a call to a blocking function such as a blocking read from a stream ?
int x;
std::cin >> x;
for example...
is it possible to force a thread to return from a call to a blocking function such as a blocking read from a stream ?
int x;
std::cin >> x;
for example...
No, it's not possible. If you want to find out whether there's data to read, use the select() syscall - if you only read when there's data waiting, you'll never block
Maybe try the istream::readsome() method. It doesn't wait for the device and only reads what's in the buffer of a buffered stream.
You can peek an istream object.
Another method is to have a separate thread permanently waiting on console input and placing the data in a queue or buffer. The interface to the buffer is then up to you, you can make it blocking, non-blocking, or timeout (or all three).
Since it's been said it is not possible, I think it should be great though to give some alternatives.
I usually do some server code and we have the same problem with synchronous calls (blocked) to the database. Sometimes (for whatever reason) the call may not return quickly enough, and you have a limited time for the processing.
The solution we have adopted is pretty simple, and involves MT of course:
As a matter of habit, we set the timer to a confortable zone between 75% and 95% of the maximum time allowed to process a request (configured by category of requests).
This allows you to neatly avoid the blocking calls. If you don't want to properly synchronize your BOM (since it involves overhead), the "best effort" answer could well be a simple retry message (that's the 95%). If you have cleanup to do or another way (cache?) to answer, you'll need synchronization in part of the BOM at least (that's the 75%).