Non-blocking IO

Hey everyone

I have an issue where I need non blocking IO, ie, the program will still continue while waiting on user input. Let me start straight up by saying that threads is not an option.

Here's what I have for a concept:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
    int i = 0;     // Purpose is to show that the io is non-blocking
    char str[24] = {0};
    
    while (true)
    {
        for (int j = 0; j < 1000000000; j++);  // Purely to make the output readable before it disappears off screen
        cin.readsome(str, 24);
        cout << i << str << endl;
    }
    return 0;
}


Since readsome will only take what is in the input buffer, and finish when it is empty, i figured it would not put anything into str if there was not yet anything entered. If something had been entered in, then it would put it in, and execution altered appropriately.

Unfortunately, when this code is run, whenever data is entered, only the counter is printed, ie, nothing is going into str.

Is there something I missed and / or is there a better way to do non blocking IO with iostream?

Cheers

Damian
Last edited on
AFAIK, there's no way to perform asynchronous I/O with iostreams without using threads. Is using a third party library acceptable?
I have no problem with third party libraries
Then take a look a PDcurses. It probably has some non-blocking functions, or at the very least functions to detect keystrokes.
I have had a look at it before. It was somewhat confusing...

What about anything in cstdio?
iostream is mostly a wrapper for cstdio functions. This is just another way of saying "no, you won't find anything useful there, either".
Neither C nor C++ were designed at the time with built-in parallelization.

If you find PDcurses too complicated, then the way to go is threads. That way you can use existing interfaces without having to learn anything new (other than the threads library, obviously). pthreads is simple to use, and so is Boost, but Boost is harder to set up.
Topic archived. No new replies allowed.