Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qt application and Multithreading error.



  • Hi, I am working multi-thread. I have a function called initThread(),
    where I am initializing the thread and then I have a thread function
    where I have the logic I want to perform in that thread. Then,
    I pass it to another function. The thing
    is the thread is starting twice on the second click and thrice on the third click and it gets increases as such.

    I will provide a sample code here, Please go through it.

    //someClass.cpp
    
    someClass::someClass(QObject *parent) : QObject(parent)
    {
    	initThread();
    }
    void someClass::initThread()
    {
    	sampleThread = new QThread(this);
        	connect(sampleThread &QThread::finished, this, [](){
            qDebug() << "sampleThread is finished";
        	});
    }
    void someClass::callSampleThreadFunction()
    {
    	sampleThreadFunction();
    }
    void someClass::sampleThreadFunction()
    {
    	connect(sampleThread &QThread::started, this, [](){
            qDebug() << "sampleThread is started";
        	});
    
    	connect(sampleThread &QThread::started, this, [](){
            	// My logic here
    		sampleThread->exit();
        	});
    	connect(sampleThread, &QThread::finished, this, &QThread::deleteLater);
    	sampleThread->start();
    }
    
    // MainWindow.cpp
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
        , class(new someClass)
    {
    
    }
    void MainWindow::on_pushButton_clicked()
    {
    	
        class->callSampleThreadFunction();
    }
    

    And I get output like this...

    // Output
    
    sampleThread is started
    sampleThread is finished
    
    sampleThread is started
    sampleThread is started
    sampleThread is finished
    
    sampleThread is started
    sampleThread is started
    sampleThread is started
    sampleThread is finished
    

    Why I am getting like this, Am I went wrong anywhere?. Thanks in advance.



  • @lakshmanGiri said in Qt application and Multithreading error.:

    Hi, I am working multi-thread. I have a function called initThread(),
    where I am initializing the thread and then I have a thread function
    where I have the logic I want to perform in that thread.

    Then, I have a standard function where I call the thread function. The thing
    is the thread is starting twice on the second click and thrice on the third click and it gets increases as such.

    What is a "thread" function and a "standard" function???

    And why do you not simply use QtConcurrent::run() if you want to start a function in another thread?
    Take a look at https://doc.qt.io/qt-5/qtconcurrentrun.html


Log in to reply