C++: Auto-interrupt a getch() call - c++

Problem
My program has multiple threads, with two currently important ones; The "Keyboard" thread is a getch() call wrapped by a while loop, and the "Conductor" thread imitates a user's input on a schedule for automation purposes. I need to find a way for the Conductor to interrupt the Keyboard thread without any intervention from the user.
Solutions
I have a couple of strategies that I anticipate the answer may take the form of.
A: A timed getch() call
I wonder if it may be possible to have the getch() call timeout after some time and continue execution of the program without any input from user. This would allow the loop to check for input from the user for some amount of time, and then check for input from the Conductor (which would otherwise not be able to communicate with the Keyboard thread because the getch() call would still be running). This could leave a potential bug in the program, if the user happens to hit the keyboard while the Keyboard thread isn't listening via getch(), but it would be one solution.
B: Insert data into input stream
It may be possible for the Conductor to send information to the Keyboard thread by using the input stream that getch() uses. I know very little about the specifics of getch() and input-output in general, but I think that there must be some way for the Conductor to imitate the user's keyboard and send a key that will be picked up by getch(). If possible, this would be the preferred solution (no foreseeable bugs, and would simplify the design of the Conductor).
Any help would be greatly appreciated, thank you!

Related

How to wait for a barcode reader input without freezing the main thread of my program?

i'm writing a program using C++ that finds an object on a video, then the user must scan, with a barcode reader, some code in a list, then if the code is correct, the information is sent to a table in MySql.
i am stuck in the part of waiting for the user to scan the barcode. if i use a loop then the program gets frezed, so maybe i must wait for some keyboard event(because the barcode behaves like it), but this function can't continue if the code hasn't been readed.
so any one can point me what is the best way to do it?..
If your barcode scanner is attached as a keyboard as many of them are, then you need asynchronous IO.
Here is example how to read from keyboard without blocking.
C non-blocking keyboard input

How do I clear user input (cin) that occurred while the process was blocked?

I have a C++ program that takes input from the user on std::cin. At some points it needs to call a function that opens a GUI window with which the user can interact. While this window is open, my application is blocked. I noticed that if the user types anything into my application's window while the other window is open, then nothing happens immediately, but when control returns to my application those keystrokes are all acted upon at once. This is not desirable. I would like for all keystrokes entered while the application is blocked to be ignored; alternatively, a way to discard them all upon the application regaining control, but retaining the capability to react to keystrokes that occur after that.
There are various questions on Stack Overflow that explain how to clear a line of input, but as far as I can tell they tend to assume things like "the unwanted input only lasts until the next newline character". In this case this might not be so, because the user could press enter several times while the application is blocked. I have tried a variety of methods (getline(), get(), readsome(), ...) but they generally seem not to detect when cin is temporarily exhausted. Rather, they wait for the user to continue supplying content for cin. For example, if I use cin.ignore(n), then not only is everything typed while the GUI window was open ignored, but the program keeps waiting afterwards while the user types content until a total of n characters have been typed. That's not what I want - I want to ignore characters based on where in time they occurred, not where in the input stream they occur.
What is the idiom for "exhaust everything that's in cin right now, but then stop looking for more stuff"? I don't know what to search for to solve this.
I saw this question, which might be similar and has an answer, but the answer asks for the use of <termios.h>, which isn't available on Windows.
There is no portable way to achieve what you are trying to do. You basically need to set the input stream to non-blocking state and keep reading as long as there are any characters.
get() and getline() will just block until there is enough input to satisfy the request. readsome() only deals with the stream's internal buffer and is only use to non-blockingly extract what was already read from the streams internal buffer.
On POSIX systems you'd just set the O_NONBLOCK with fcntl() and keep read()ing from file descriptor 0 until the read returns a value <= 0 (if it is less than 0 there was an error; otherwise there is no input). Since the OS normally buffers input on a console, you'd also need to set the stream to non-canonical mode (using tcsetattr()). Once you are done you'd probably restore the original settings.
How to something similar on non-POSIX systems I don't know.

How do I separate input from output in a C++ console application? Can I have two cursors?

I'm coming from C and don't have too much programming knowledge, so bear with me if my idea is nonsense.
Right now, I'm trying to write a simple threaded application with double-buffered console output. I've got a thread which resets the cursor position, draws the buffer and then waits n milliseconds:
gotoxy(0, 0);
std::cout << *draw_buffer;
std::this_thread::sleep_for(std::chrono::milliseconds(33));
This works perfectly well. The buffer is filled independently by another thread and also causes no problems.
Now I want the user to be able to feed the application information. However, my drawing thread always puts the cursor back to the start, so the user input and the application output will interfere. I'm aware there are libraries like curses, but I'd prefer to write this myself, if possible. Unfortunately, I haven't found any solution to this. I guess there is no way to have two console cursors moving independently? How else could I approach this problem?
I think what you will need to do two things:
Create a mutex that controls which thread is writing to stdout.
Change the input mode so that when you invoke getchar, it returns immediately (rather than waiting for the user to press enter). You can then wait for the other thread to release the mutex, then move the cursor and echo the character the user pressed at the appropriate part of the screen.
You can change the input mode using tcsetattr, although this is from termios which is for *nix systems. Since you're using windows, this may not work for you unless you're using cygwin.
maybe check this out: What is the Windows equivalent to the capabilities defined in sys/select.h and termios.h

Bypassing blocking input stream with C++/Boost

I'm currently writing something of a quiz program. This program throws questions at the user until a specified time limit runs out. How it's set up now is the quizzing functionality runs in a boost thread and the timing aspect is handled by a timed_join() on that thread. The problem I'm encountering is when the user is answering a question using cin, the thread will go past the time limit that has been established. Is there a way to have it interrupt the cin call?
You can use Boost.Asio to read from cin asynchronously as described here - updated link to example code is here.
You can read the input character by character in a non-blocking read by using getchar, getch or getche. If you've been looping long enough to reach the timeout, then stop looping :).
You might need to use other input methods. The readline library might be able to help you. Or if you are on Linux, you can go down to pure file descriptors, make STDIN_FILENO non-blocking like a non-blocking socket and use the select system-call and then you can get both the timeout and know when input is ready.

C++ What can I use instead sleep() function?

I'm building scrobbler, and I want my program to wait 10 seconds after song change, before scrobbling. I have been using sleep but I realized that if song change during these 10 seconds, program submit old song and get new one. I want If I change song, code start all over again.
I'm using Music Player Daemon (MPD) and libmpd to get songs' tags.
Note: program is under Unix.
It depens a lot on how your program works, but in principle, the easiest way would be to keep using sleep and check whether the user changed the song before sending out that data (after sleep has returned). So, instead of "try to sleep better", the goal would be "check that the data you send is really valid before sending".
A different possibility would be to wait on an epoll using either the timeout for sleeping or better yet on a timerfd, and notify song change via an eventfd. This has the advantage that it is "free" if you need reliable inter-thread communication and readiness notification anyway, which you most probably do (obviously you must have at least one additional GUI thread, or the user would not be able to change songs while you're blocking).
Damon's suggestion is a good one and may be a better overall design. If you're looking for something quick though, you could consider simply sending a signal to your application when the song changes. That will interrupt the sleep() system call and cause it to return early. Your application would then just need to handle the early return as appropriate. Depending on your implementation, this may not be appropriate but it might give you a quick fix.