QThread - Why do threads wait one another to start running?



  • Hi

    I have the following code. When I run the code, first thread 0 starts and finishes and then thread 1 starts and finishes.
    I designed to code such that running time for thread 0 is much longer than thread 1 and I was expecting, while thread 0 is running, I should see thread 1 starts running but it doesn't

    [code]#include <QtCore/QCoreApplication>
    #include <QThread>
    #include <iostream>
    #include <cstdlib>
    #include <windows.h>

    using namespace std;

    static int GlobalThreadId = 0;

    class MyThread : public QThread {
    private:
    int t_id;
    public:
    MyThread();
    void run();
    };

    MyThread::MyThread(){
    cout << "Thread initialized" << endl;
    t_id = GlobalThreadId;
    GlobalThreadId++;
    }

    void MyThread::run (){
    cout << "Thread number " << t_id << " started." << endl;

    int val = (1-t_id)*1000;
    for (int y=0; y<(val*1000); y++)
            for (int l=0; l<100;l++){}
    
    cout << "Thread number " << t_id << " completed." << endl;
    

    }

    int main(int argc, char *argv[])
    {
    MyThread *t[8];
    int i;

    cout << "Number of Threads that will be created : " << QThread::idealThreadCount() << endl;
    
    int CreatedThreadNumber = 0;
    for (int x=0; x < QThread::idealThreadCount() ; x++) {
        t[x] = new MyThread;
        CreatedThreadNumber++;
    }
    
    for (int l=0; l < CreatedThreadNumber; l++) {
        t[l]->run();
    }
    
    cin >> i;
    return 0;
    

    }[/code]



  • Use the start() method to begin execution, not run() method.

    In this link you can find good tutorials about threads: http://www.voidrealms.com/tutorials.aspx?filter=qt


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.