Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    why threads id are same?

    General and Desktop
    2
    2
    1279
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • I
      iskenderoguz last edited by

      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 ?

      JKSH 1 Reply Last reply Reply Quote 0
      • JKSH
        JKSH Moderators @iskenderoguz last edited by

        @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.

        Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

        1 Reply Last reply Reply Quote 1
        • First post
          Last post