Is there a way for me to create a second thread that
would read console inputs but won't be in blocking
mode. (I would be able to terminate the thread whenever
I want)
I've already done the second thread that reads console
inputs but it is blocking..
I saw some functions around including GetStdHandle,
WaitForSingleObject but I don't know where to look
first... Is there a way to wait for a console input handle
for example 500 ms then loop ?
Thank you,
Mike
Okay here is what I did... but I don't know
if its "elegent" or bullet proof so I need an opinion :
DWORD WINAPI ThreadProc(LPVOID lpParameter){
char buff[1024] = {0};
ofstream fout( "test.txt", ios::trunc);
fout << "Thread listening" << endl;
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
if(hStdin == INVALID_HANDLE_VALUE)
ExitThread(1);
FlushConsoleInputBuffer(hStdin);
while(true){
if(WaitForSingleObject(hStdin, 1000) == WAIT_OBJECT_0){
cin >> buff;
fout << buff << endl;
}
else{
fout << "Polling..." << endl;
}
if(WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0)
break;
}
fout << "Thread terminated" << endl;
fout.close();
ExitThread(0);
}
Here the thread wait 1 sec. for user input. After, it
quits if the main thread wants him to quit. If not, it
loops again.
Is it a correct way to do it ?
Mike
Yes.
This line gets you a Win32 handle to the input device:
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
When there is input to be read the console handle will be signaled. One way
that you can wait for input is by passing that handle to
WaitForSingleObject[Ex]()
> Is there a way to wait for a console input handle
> for example 500 ms then loop ?
If you pass a zero timeout to the function you can poll the console. Or you
can pass 500ms to wait a half second.
In an application of mine that reads the console asynchronously I call
GetNumberOfConsoleInputEvents() when the handle is signalled to determine
the number n of input events pending, and then ReadConsoleInput() n times
for 1 event each. In this way, I can be sure never to block on the read.
Note that the docs mention that ReadConsoleInput() blocks until there is at
least one input event to return.
Regards,
Will
A better way would be to use WaitForMultipleObjects, blocking forever. :
this will prevent any polling :
HANDLE handles[2];
handles[0]=hStdin;
handles[1]=hEvent;
while (true)
{
switch (WaitForMultipleObjects(2, handles, FALSE, INFINITE))
{
case(WAIT_OBJECT_0) :
{
//hStdin has been raised : process the console input however you
want...
break;
}
case(WAIT_OBJECT_1):
{
//hEvent has been raised : exit
return 0: //simply return from the function is better than
calling ExitThread, because it will allow cleanup
}
case(WAIT_FAILED):
default:
{
//processing error : handle it
}
}
}
Arnaud
MVP - VC
Mike