How to use a process (QProcess) in a new thread (QThread)?
Solution 1
void processmethodONE()
{
QThread* thread = new QThread;
Prozess.moveToThread(thread);
Prozess.start(ProcessComand);
Here you moved the QProcess to another thread. But then you call start() on it. That's already not thread-safe.
while(!Prozess.waitForFinished(2000))
{
std::cerr << "Process running " << std::endl;
}
This blocks and makes using a thread useless. Also, it's not thread-safe.
You should instead not use threads but:
- remove the waitForFinished() call
- Connect the finished() and error() signals of the QProcess to slots which then start the next step, i.e. processMethodTWO.
I would also advise against reusing QProcess objects and just create a new one for each step.
Solution 2
While I still don't fully understand your recently updated code example, I feel this might be your issue:
while(!Prozess.waitForFinished(2000))
{
std::cerr << "Process running " << std::endl;
}
Wherever you are really calling this in your original code is blocking while waiting for Prozess to finish.
Use a brand new QProcess instance for each one, and connect their finished() signals to a SLOT that will get called when they have finished. Don't manually poll them and block. This will allow you to completely get rid of QThreads altogether.
Streight
Study machine- and process-engineering, Greetings from Germany
Updated on July 16, 2022Comments
-
Streight almost 2 years
I have the following code:
void Processmethod() { QDialog *ProcessMessage = new QDialog; Ui::DialogProcessMessage Dialog; Dialog.setupUi(ProcessMessage); ProcessMessage->setModal(true); ProcessMessage->setAttribute(Qt::WA_DeleteOnClose); ProcessMessage->show(); qApp->processEvents(); processmethodONE(); processmethodTWO(); processmethodTHREE(); } void processmethodONE() { QString ProcessCommand = "w8 " + blablubli"; Prozess.setWorkingDirectory(Path); //QProcess "Prozess" is globaly defined Prozess.setStandardOutputFile(Path); //in my class QThread* thread = new QThread; Prozess.moveToThread(thread); Prozess.start(ProcessCommand); while(!Prozess.waitForFinished(2000)) { std::cerr << "Process running " << std::endl; } QProcess::ExitStatus Status = Prozess.exitStatus(); if (Status == 0) { std::cout << "File created!" << std::endl; } }
In this source code I try to open a popup dialog before some processes are starting. problem is that the dialog is not clickable, but on the dialog I want to create a button to abort the running method. As you can see I tried using QThread to run the process(es) in another thread, but still I can't click the dialog. Furthermore if I open my application (GUI) with the "application/x-executable"-file the dialogs content is missing when activating the above shown method. How can I fix these problems? Where am I wrong? greetings