why threads id are same?



  • I create a class to use multi threads

    class ClThread : public QThread
    {
    public:
        ClThread();
        void run();
    signals:
    public slots:
    };
    
    I wrote thread id in constructor
    ClThread::ClThread()
    {
        qDebug()<<"thread : "<<thread()->currentThreadId();
    }
    
    I call it from main class
    
    ClThread *clthread1 = new ClThread();
    ClThread *clthread2 = new ClThread();
    

    Also I tried QRunnable

    class ClThread : public QRunnable
    {
    public:
        ClThread();
        void run();
    signals:
    public slots:
    };
    
    ClThread::ClThread()
    {
        qDebug()<<"thread : "<<QThread::currentThreadId();
    }
    
    ClThread *clthread1 = new ClThread();
    ClThread *clthread2 = new ClThread();
    
    QThreadPool::globalInstance()->start(clthread1);
    QThreadPool::globalInstance()->start(clthread2);
    

    But clthread1 and clthread2 threads id are same always. this is normal ? these are different threads ?


  • Moderators

    @iskenderoguz said:

    I call it from main class
    
    ClThread *clthread1 = new ClThread();
    ClThread *clthread2 = new ClThread();
    

    ...
    But clthread1 and clthread2 threads id are same always. this is normal ?

    Yes, this is normal.

    Your code runs the constructors in the main thread. It does not start any new threads. Think of it this way:

    QFile* file = new QFile("myfile.txt"); // This does NOT create a new file on your hard drive
    QThread* thread = new QThread(); // This does NOT create a new thread in your program
    
    // ===
    
    file->open(QFile::WriteOnly); // This creates a new file on your hard drive
    thread->start(); // This creates a new thread in your program
    

    If you want to start your new thread, you must call QThread::start(). Then, the code inside QThread::run() will start running in a new thread.


Log in to reply
 

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