Possible to stop cin from waiting input? - c++

In a graphical application I execute debug commands using the console input. When the console is created a new thread is also created to gather the user commands that handles all that input, the graphical application continues running parallel. I use boost::thread library.
It works good so far, however I haven't found a nice solution to stop the execution of this thread. The thread is always waiting for a user input:
while(appRunning)
{
std::cin>>theUserCommand;
// ...do stuff
}
Then when the graphical application ends, it will stop all console functions, in which I include the thread:
appRunning = false;
// do some more related clean up
myListeningThread->join();
As you can see the std::cin will be waiting for user input, after the join has being called.
One of the solutions I tried is to create events "synthetizing keystrokes", the std::cin will get whatever value you send with an ENTER, the thread will end nicely, this solutions is horrible and I don't want to keep it.
Besides, it did work in one of the environments the tool is executed, but fails when I tried using it along with a UI API. Could you guys guide me how can I fix this in a correct way? Can't really say for sure if in the C++ documentation there is a function to stop std::cin waiting for user input, and just and continue the program execution, is it even possible?
EDIT: Fine I find that keybd_event is a bit misleading for some environments, explicitly specifying the input handler with the WriteConsoleInput works good.

I am not much of a Windows programmer, I know a whole lot more about Unix. And I am totally unfamiliar with boost::thread. That said, based on the advice at the bottom of this MSDN page, here is my recommendation:
Create an event object before you create the console-reading thread.
When you want to shut down, call SetEvent on the event object immediately before calling the thread's ->join method.
Change the main loop in your console-reading thread to block in WaitForMultipleObjects rather than istream::operator>>, something like this:
for (;;) {
HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = that_event_object_I_mentioned;
DWORD which = WaitForMultipleObjects(2, h, FALSE, INFINITE);
if (which == WAIT_OBJECT_0)
processConsoleCommand();
else if (which == WAIT_OBJECT_0 + 1)
break;
else
abort();
}
This thread must take care not to do any blocking operation other than the WaitForMultipleObjects call. Per the discussion in the comments below, that means processConsoleCommand can't use cin at all. You will need to use the low-level console input functions instead, notably GetNumberOfConsoleInputEvents and ReadConsoleInput, to ensure that you do not block; you will need to accumulate characters across many calls to processConsoleCommand until you read a carriage return; and you will also need to do your own echoing.

Related

mciSendString doesn't pause sound played from a thread

Recently I already asked for a solution similar to this questions:
Is there a way to pause/stop a mp3 file playing with mcisendstring with the "wait" option?
I want to implement a function in my audio player which allows people to have sound playing continuosly, while a slider moves according to the current second the track is running in, and also with the functionality to go to the next track after the current track is over
After (as you can read in the link) trying to do it with
mciSendString("play mp3 wait", NULL, 0, NULL);
which failed due to the problem that the track can't be paused or stopped until it is finished, I am now trying to implement it another way. Currently, when I start to play the track, I also start another thread, which is starting a counter. The counter is getting the length of the track in seconds, and is counting down the time, also offering a mutex for pausing/resuming the counter. In order to stop my MusicCycle from simply looping uncontrolled, I am joining the thread, therefore waiting for its termination.
void Music::MusicCycle(std::wstring trackPath)
{
while (true)
{
OpenMP3(trackPath);
mciSendString("play mp3", NULL, 0, NULL);
m_counterThread = boost::thread(boost::bind(&Counter::StartCount, m_counter, <length of track in seconds>));
m_counterThread.join();
//... Get new track here
}
}
Note that this whole method is created in a thread as well:
m_cycleThread = boost::thread(boost::bind(&Music::MusicCycle, this, trackPath));
The thread started by the MusicCycle function is looking like this:
void Counter::StartCount(int seconds)
{
boost::mutex::scoped_lock lock(m_mutex);
for (int i = 0; i < seconds; i++)
{
while (m_counterLock)
{
m_condVar.wait(lock);
}
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
}
Also, I added another functionality to lock/unlock the mutex here with my Pause/Resume methods, which also call the corresponding mciSendString functions
mciSendString("resume mp3", NULL, 0, NULL);
mciSendString("pause mp3", NULL, 0, NULL);
When I would call pause now, mciSendString would pause the track, and also lock the counter so it won't keep on counting down.
However, the problem is that it still doesn't work. The pause simply doesn't affect the playing of music, despite my efforts to think up a solution without using the wait option in the mciSendString
Any advice?
EDIT: Turns out this is actually happening due to threading. I've been doing some C# for a good amount of time and you could use Invokes to work around thread problems. Maybe this is possible here as well?
EDIT2: I read up a bit and it seems like there is an option to Post a method in the message queue of another thread via PostMessage WinAPI call. Is this a possiblity here? If yes, could anyone provide a good example? I read up a bit but I don't really understand alot so far
Is there something like this in C++ as well?
EDIT: Turns out this is actually happening due to threading. I've been doing some C# for a good amount of time and you could use Invokes to work around thread problems.
Yes. Ifff you need a user-land thread for the asynchronous events then a queued message is your course of action (like C#'s (or Java's etc.) invoke-on-UI-thread). That's hard work.
EDIT2: I read up a bit and it seems like there is an option to Post a method in the message queue of another thread via PostMessage WinAPI call. Is this a possiblity here? If yes, could anyone provide a good example? I read up a bit but I don't really understand alot so far
Is there something like this in C++ as well?
What you're referring to is just the general message-pump/event-loop that underlies almost¹ all UI frameworks. C++ doesn't "have" GUI natively, but certainly libraries exist that have similar facilities.
Boost Asio was one mentionable. If you already have a GUI framework, it'll have it's own event loop (Qt, MFC etc. have it).
Regardless of what is used, all Win32 GUI applications end up using the message pump you referred to which does indeed allow messages to be posted.
This is almost always the wrong level of abstraction, unless you're actively developing your GUI framework².
You can always build your own. Just have some kind of (priority) queue to receive messages and have a main loop processing these. Call them events and pronto: event-driven design.
¹ there's a wave back at the moment with new-fangled back-to-basics like https://github.com/ocornut/imgui
² the fact that this question exists tells me you are not doing that

Best way to exit application at CTRL+C interrupt on Linux. (C/C++)

My application checks for user input in its main thread:
while (running)
{
std::string console;
if (std::getline(std::cin, console))
{
process(&console);
}
}
Before that I have setup a sigaction to detect CTRL+C in conjunction with a function handler to shutdown other threads.
Now, when a SIGINT occurs the application crashes; GDB output:
I was looking around and found other solutions such as non-blocking input reading: (pseudo-code)
while (running)
{
if (input_avail())
{
getinput
process
}
else
sleep(1);
}
But even that fails for me at the sleep function (nanosleep):
So I'm quite curious on how other people achieve this?
(Using g++ v4.8.2 Kernel 3.10)
Additional info requested:
Before the main thread loop:
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signalinfo;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGTERM, &sigIntHandler, NULL);
sigaction(SIGQUIT, &sigIntHandler, NULL);
sigaction(SIGINT, &sigIntHandler, NULL);
Signal handler:
void signalinfo(int signum)
{
// Only setting a flag so threads know to exit.
pCore->Termination(signum);
}
Not sure if it answers your question, but the documentation of the XBoard protocol explains some common strategies how engine engine handle reading from stdin.
It basically sketches how you might implement your non-blocking pseudo code.
Source: XBoard protocol (6. Hints on input/output)
... on the input side, you are likely to want to poll during your search and stop it if new input has come in. If you implement pondering, you'll need this so that pondering stops when the user makes a move. You should also poll during normal thinking on your move, so that you can implement the "?" (move now) command, and so that you can respond promptly to a "result", "force", or "quit" command if xboard wants to end the game or terminate your engine. Buffered input makes polling more complicated -- when you poll, you must stop your search if there are either characters in the buffer or characters available from the underlying file descriptor.
The most direct way to fix this problem is to use unbuffered operating system calls to read (and poll) the underlying file descriptor directly. On Unix, use read(0, ...) to read from standard input, and use select() to poll it. See the man pages read(2) and select(2). (Don't follow the example of GNU Chess 4 and use the FIONREAD ioctl to poll for input. It is not very portable; that is, it does not exist on all versions of Unix, and is broken on some that do have it.) On Win32, you can use either the Unix-like _read(0, ...) or the native Win32 ReadFile() to read. Unfortunately, under Win32, the function to use for polling is different depending on whether the input device is a pipe, a console, or something else. (More Microsoft brain damage here -- did they never hear of device independence?) For pipes, you can use PeekNamedPipe to poll (even when the pipe is unnamed). For consoles, you can use GetNumberOfConsoleInputEvents. For sockets only, you can use select(). It might be possible to use WaitForSingleObject more generally, but I have not tried it. Some code to do these things can be found in Crafty's utility.c, but I don't guarantee that it's all correct or optimal.
A second way to fix the problem might be to ask your I/O library not to buffer on input. It should then be safe to poll the underlying file descriptor as described above. With C, you can try calling setbuf(stdin, NULL). However, I have never tried this. Also, there could be problems if you use scanf(), at least with certain patterns, because scanf() sometimes needs to read one extra character and "push it back" into the buffer; hence, there is a one-character pushback buffer even if you asked for stdio to be unbuffered. With C++, you can try cin.rdbuf()->setbuf(NULL, 0), but again, I have never tried this.
A third way to fix the problem is to check whether there are characters in the buffer whenever you poll. C I/O libraries generally do not provide any portable way to do this. Under C++, you can use cin.rdbuf()->in_avail(). This method has been reported to work with EXchess. Remember that if there are no characters in the buffer, you still have to poll the underlying file descriptor too, using the method described above.
A fourth way to fix the problem is to use a separate thread to read from stdin. This way works well if you are familiar with thread programming. This thread can be blocked waiting for input to come in at all times, while the main thread of your engine does its thinking. When input arrives, you have the thread put the input into a buffer and set a flag in a global variable. Your search routine then periodically tests the global variable to see if there is input to process, and stops if there is. WinBoard and my Win32 ports of ICC timestamp and FICS timeseal use threads to handle multiple input sources.

How does the message loop use threads?

I'm somewhat confused and wondering if I've been misinformed, in a separate post I was told "New threads are only created when you make them explicitly. C++ programs are by default single threaded." When I open my program that doesn't explicitly create new threads in ollydbg I noticed multiple times that there are often 2 threads running. I wanted to understand how the message loop works without stopping up execution, the explanation I got was very insufficient at explaining how it works.
Does the message loop create a new thread or does it take up the main thread? If it takes the main thread does it do so after everything else has been executed regardless of code order? If it doesn't do this but still takes up the main thread does it spawn a new thread so that the program can execute instead of getting stuck in the message loop?
EDIT: Solved most of my questions with experimentation. The message loop occupies the main thread and any code after the code:
while (GetMessage (&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
Will not execute unless something special is done to cause it to execute because the program is stuck in the message loop. Putting an infinite loop in a window procedure that gets executed causes the program to crash. I still don't understand the mystery of the multiple threads when in olly to the degree I would prefer though.
Perhaps the place to start is to realize that "the message loop" isn't a thing as such; it's really just something that a thread does.
Threads in windows generally fall into one of two categories: those that own UI, and those that do background work (eg network operations).
A simple UI app typically has just one thread, which is a UI thread. For the UI to work, the thread needs to wait until there's some input to handle (mouse click, keyboard input, etc), handle the input (eg. update the state and redraw the window), and then go back to waiting for more input. This whole act of "wait for input, process it, repeat" is the message loop. (Also worth mentioning at this stage is the message queue: each thread has its own input queue which stores up the input messages for a thread; and the act of a thread "waiting for input" is really about checking if there's anything in the queue, and if not, waiting till there is.) In win32 speak, if a thread is actively processing input this way, it's also said to be "pumping messages".
A typical simple windows app's mainline code will first do basic initialization, create the main window, and then do the wait-for-input-and-process-it message loop. It does this usually until the user closes the main window, at which point the thread exits the loop, and carries on executing the code that comes afterwards, which is usually cleanup code.
A common architecture in windows apps is to have a main UI thread - usually this is the main thread - and it creates and owns all the UI, and has a message loop that dispatches messages for all of the UI that the thread created. If an app needs to do something that could potentially block, such as reading from a socket, a worker thread is often used for that purpose: you don't want the UI thread to block (eg. while waiting for input from a socket), as it wouldn't be processing input during that time and the UI would end up being unresponsive.
You could write an app that had more than one UI thread in it - and each thread that creates windows would then need its own message loop - but it's a fairly advanced technique and not all that useful for most basic apps.
The other threads you are seeing are likely some sort of helper threads that are created by Windows to do background tasks; and for the most part, you can ignore them. If you initialize COM, for example, windows may end up creating a worker thread to manage some COM internal stuff, and it may also create some invisible HWNDs too.
Typically the thread that starts the program only runs the message loop, taking up the main thread. Anything not part of handling messages or updating the UI is typically done by other threads. The additional thread that you see even if your application doesn't create any threads could be created by a library or the operating system. Windows will create threads inside your process to handle things like dispatching events to your message loop.

moving multiple files under while loop using wxwidget

I have been writing a c++ code for myself,which iterates in a directory and will move files in to a directory of the same name as the file
\\\\
void foldersFrame::OnButton2Click(wxCommandEvent& event)
{
wxFileName mkr;
StaticText1->SetLabel(_("0"));
wxString fn;
wxString newf;
wxDir *dir=new wxDir(TextCtrl1->GetLabel());
bool cont = dir->GetFirst(&fn);
while (cont)
{
int mm=fn.Find('.',true);
newf=fn.Mid(0,mm);
if(! mkr.DirExists(dir->GetName()+_("\\")+fn)){
StaticText2->SetLabel(_("copying ")+fn);
if (! mkr.DirExists(dir->GetName()+_("\\")+newf)){
mkr.Mkdir(dir->GetName()+_("\\")+newf);
if (wxCopyFile(dir->GetName()+_("\\")+fn,dir->GetName()+_("\\")+newf+_("\\")+fn)){
wxRemoveFile(dir->GetName()+_("\\")+fn);
}
newf=StaticText1->GetLabel();
long d1;
if(!newf.ToLong(&d1));
d1+=1;
StaticText1->SetLabel(wxString::Format(wxT("%i"),d1));
}
}
cont = dir->GetNext(&fn);
}
wxSafeShowMessage(_("Message"),_("Finished"));
}
But the code i have written seem to be very inefficient.It takes a lot of time to move files,and the window doesn't respond while copying.Someone please help me rewrite it..!!!!
To keep the application window responsive, but without going to the extra trouble of doing the file copy in a separate thread, try using Yield. Needs care!
wxApp::Yield
bool Yield(bool onlyIfNeeded = false)
Yields control to pending messages in the windowing system. This can be useful, for example, when a time-consuming process writes to a text window. Without an occasional yield, the text window will not be updated properly, and on systems with cooperative multitasking, such as Windows 3.1 other processes will not respond.
Caution should be exercised, however, since yielding may allow the user to perform actions which are not compatible with the current task. Disabling menu items or whole menus during processing can avoid unwanted reentrance of code: see ::wxSafeYield for a better function.
Note that Yield() will not flush the message logs. This is intentional as calling Yield() is usually done to quickly update the screen and popping up a message box dialog may be undesirable. If you do wish to flush the log messages immediately (otherwise it will be done during the next idle loop iteration), call wxLog::FlushActive.
Calling Yield() recursively is normally an error and an assert failure is raised in debug build if such situation is detected. However if the onlyIfNeeded parameter is true, the method will just silently return false instead.
You have two standard ways to implement a long running task.
First one, and by far the best, is to perform this task in a separate background thread. You can update the state of the GUI controls in the main thread by posting wxThreadEvent containing the progress data to the main window easily. The only complication -- but a pretty important one -- in this case is to handle closing the window/application termination/thread exit correctly.
Second one, which could do in a pinch, is to do the task in wxEVT_IDLE handler piece by piece and call wxIdleEvent::RequestMore() after each step. This is not as responsive as using a separate thread because you still block the event handling during the handler execution and the code needs to be rewritten in a different way to be able to resume from where it left off.
Using wxYield() is a pretty bad idea and should be avoided unless no other solution can be implemented.

How can I fix my window focus problem?

I have a very frustrating bug in an application I am working on. The routine is supposed to do something in one window, and then return focus to the other at the end of the method, but when I started to use a large data set the other day, the focus stopped returning at the end. I stepped through the code one line at a time, and the errors stopped. so, i figure its a timing issue of some kind. I trace through until i find what i suspect is the culprit. A call to ShellExecute(...), that terminates an image editor i use.
(http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx)
Now, if I step past this call, and then continue to run the program, everything works fine, but if I just run past this line, the error occurs. how can this be? I have a call to SetFocus() at the very end of this method. shouldnt the program hit this no matter what?
This is all so very frustrating...
First thing that should be clear is that Win32 API calls that are related to windows/messages/focus and etc. do not depend on timing.
Every thread has its own window/messaging subsystem, there's no race conditions here.
What you describe is something else. You actually launch another process (application), which runs concurrently with yours.
Note that ShellExecute is an asynchronous function. It returns immediately after creating the process, and from now on your application and the process you've created run concurrently.
Now, since only one window in the system may have a focus at a time - it's very likely that the process you've created just steals the focus from you.
In order to avoid this - you should first wait for that process to finish working, and only then restore the focus to your window and continue working.
For this you have to obtain the handle of the created process, and call a Win32 waiting function on it. ShellExecute doesn't return you the handle of the created process. However ShellExecuteEx - does.
BTW it also allows you to launch a process with instruction for it not to show the UI, if this is what you want.
You should write it like this:
SHELLEXECUTEINFO sei;
memset(&sei, 0, sizeof(sei));
sei.cbSize = sizeof(sei);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpFile = L"notepad.exe";
sei.nShow = SW_SHOWNORMAL; // or SW_HIDE if you don't want to show it
if (ShellExecuteEx(&sei))
{
// wait for completion
WaitForSingleObject(sei.hProcess, INFINITE);
CloseHandle(sei.hProcess);
}
This should be helpful
P.S. Of course you should close the handle of the created process. That is, CloseHandle must be called after WaitForSingleObject.
As you say, the problem sounds like one of timing.
I'm not familiar with the ShellExecute function, but from the page you linked:
"Because ShellExecute can delegate execution to Shell extensions (data sources, context menu handlers, verb implementations) that are activated using Component Object Model (COM), COM should be initialized before ShellExecute is called. Some Shell extensions require the COM single-threaded apartment (STA) type."
Maybe that's related?