PDA

View Full Version : My thread for non-blocking stdin input keeps running after program terminates



lamm
24th March 2010, 16:51
Hello, I am new in this forum, and I am very enthusiastic about Qt.
However, I have the following problem. Since I understand that there is no built-in facility to check for input on stdin, I wrote a thread for it. This works fine, but after program termination the error message
"QThread: Destroyed while thread is still running" appears.
In this thread I wrote this simple run function:

void InputThread::run()
{ fgets(inputLine, 200, stdin);
}

Since the input data read from stdin, if available, starts with 'x', I test whether input is available as follows:

if (inputThread->inputLine[0] == 'x') ... // input available in inputLine

It looks like, due to the fgets input command, the thread keeps running, despite my attempts to stop it by calling inputThread.exit() or inputThread.quit.
Can anyone please help? Any solution for checking if stdin input is available is welcome, provided it works on both Linux and Windows.

toutarrive
24th March 2010, 18:09
To finish a thread properly in Qt, use a flag inside the run() function when you want to make it stop.
You set this flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.



void myThread::run()
{
while (! isThreadstopped)
{
// do your threaded stuff;
}

} // thread has terminated.

lamm
24th March 2010, 18:30
Thank you for your attempt to help me, toutarrive, but this does not work. The point is that, in the case there is no input data available on stdin, the thread keeps waiting for this input data (which may never appear).
Therefore, if there will be no input data, this test "while (!isThreadstopped) of yours is done only once. I nevertheless tried this loop, but, as I expected, it did not help.

toutarrive
24th March 2010, 18:51
Whenever you want to stop the thread, send a signal to the thread and set the flag ( isThreadstopped to true, member of your thread class ) in the signal handler.

JD2000
24th March 2010, 19:54
Try putting an exec(); statement after the fgets().

inputThread.exit() should then work.

lamm
24th March 2010, 20:25
Thanks JD200, but the point is that any statement immediately following fgets() is never executed if there is no input available on stdin.
I nevertheless tried your suggestion (inserting exec()), but without success.

Lesiok
25th March 2010, 07:04
So maybe You can not to use fgets() ?

boudie
26th March 2010, 07:49
You can try to use an external process to read user input. In Linux that would/could be "read".
At program start you create a QProcess and connect its signals to your MainWindow, so you can read the users input.
When quiting the application, you terminate -close- the QProcess.

Hope this helps... :)

wysota
26th March 2010, 12:45
Did you try using QSocketNotifier with STDIN as the socket descriptor? You don't need a thread for that...