Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to keep one class instance thread-safe in mutilthread with Qt?
Forum Updated to NodeBB v4.3 + New Features

How to keep one class instance thread-safe in mutilthread with Qt?

Scheduled Pinned Locked Moved Solved General and Desktop
11 Posts 3 Posters 4.3k Views 1 Watching
  • 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.
  • S Offline
    S Offline
    SpartaWHY117
    wrote on last edited by SpartaWHY117
    #1

    In my current project, i have one core class instance in the program life cycle. And this is a Qt console application with mutilthreads.

    At first, I create core class instance in the main thread,then use another two threads to do some calculation with the core class member functions and change it's member variable . And i want the core instance keep consistency in two thread. So what's the simple way to do this in Qt?

    some snippet of my code:

    main function:

    QCoreApplication a(argc, argv);
    	//控制输出信息输出到文本文件
    	qInstallMessageHandler(myMessageOutput);
    
        ProgramCore window_main;
        window_main.ComponentDisplay();
        window_main.AutoConfig();
    
        thread threadA;
        thread threadB;
    

    core class:

    class ProgramCore:public QObject
    {
        Q_OBJECT
    //...some function 
    
    //member
    private:
      
       void writeSystemLog();
       void writeProcessLog(QString pid);
       void updateinfo();
       QStringList componentStringList;
        QTimer *realTimeInfoTimer;
    //other customer component class
        HardWareDetection hardDetection;
        XML_Util xmlUtil;
        PowerModel localPowerModel;
    //
    }
    
    jsulmJ 1 Reply Last reply
    0
    • S SpartaWHY117

      In my current project, i have one core class instance in the program life cycle. And this is a Qt console application with mutilthreads.

      At first, I create core class instance in the main thread,then use another two threads to do some calculation with the core class member functions and change it's member variable . And i want the core instance keep consistency in two thread. So what's the simple way to do this in Qt?

      some snippet of my code:

      main function:

      QCoreApplication a(argc, argv);
      	//控制输出信息输出到文本文件
      	qInstallMessageHandler(myMessageOutput);
      
          ProgramCore window_main;
          window_main.ComponentDisplay();
          window_main.AutoConfig();
      
          thread threadA;
          thread threadB;
      

      core class:

      class ProgramCore:public QObject
      {
          Q_OBJECT
      //...some function 
      
      //member
      private:
        
         void writeSystemLog();
         void writeProcessLog(QString pid);
         void updateinfo();
         QStringList componentStringList;
          QTimer *realTimeInfoTimer;
      //other customer component class
          HardWareDetection hardDetection;
          XML_Util xmlUtil;
          PowerModel localPowerModel;
      //
      }
      
      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @SpartaWHY117 Well, you need to protect all parts in your ProgramCore class where its member variables are modified and which can be executed in parallel from several threads. To do so you can protect those critical parts using QMutex and QMutexLocker.
      For more details see: http://doc.qt.io/qt-5.9/qmutexlocker.html

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      S 1 Reply Last reply
      3
      • jsulmJ jsulm

        @SpartaWHY117 Well, you need to protect all parts in your ProgramCore class where its member variables are modified and which can be executed in parallel from several threads. To do so you can protect those critical parts using QMutex and QMutexLocker.
        For more details see: http://doc.qt.io/qt-5.9/qmutexlocker.html

        S Offline
        S Offline
        SpartaWHY117
        wrote on last edited by
        #3

        @jsulm how about change that core class into singleton? when use the method need to get the static instance

        jsulmJ 1 Reply Last reply
        0
        • S SpartaWHY117

          @jsulm how about change that core class into singleton? when use the method need to get the static instance

          jsulmJ Offline
          jsulmJ Offline
          jsulm
          Lifetime Qt Champion
          wrote on last edited by
          #4

          @SpartaWHY117 You can use singleton if you like, but it is not really a good pattern.
          You need to serialize part of the getter:

          MySingleton* MySingleton::getInstance()
          {
              {
                  QMutexLocker locker(mutex);
                  if (instance == nullptr)
                      instance = new MySingleton();
              }
              return instance;
          }
          

          https://forum.qt.io/topic/113070/qt-code-of-conduct

          S 1 Reply Last reply
          0
          • jsulmJ jsulm

            @SpartaWHY117 You can use singleton if you like, but it is not really a good pattern.
            You need to serialize part of the getter:

            MySingleton* MySingleton::getInstance()
            {
                {
                    QMutexLocker locker(mutex);
                    if (instance == nullptr)
                        instance = new MySingleton();
                }
                return instance;
            }
            
            S Offline
            S Offline
            SpartaWHY117
            wrote on last edited by
            #5

            @jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.

            jsulmJ kshegunovK 2 Replies Last reply
            0
            • S SpartaWHY117

              @jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.

              jsulmJ Offline
              jsulmJ Offline
              jsulm
              Lifetime Qt Champion
              wrote on last edited by
              #6

              @SpartaWHY117 https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern

              https://forum.qt.io/topic/113070/qt-code-of-conduct

              1 Reply Last reply
              2
              • S SpartaWHY117

                @jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.

                kshegunovK Offline
                kshegunovK Offline
                kshegunov
                Moderators
                wrote on last edited by
                #7

                @SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:

                @jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.

                Make your variables global then, what's the difference between a singleton and that ...? At least that way it looks and feels like C, while the singleton gives you a fake "object-oriented vibe". It's just plain C - a global variable with global functions.

                Read and abide by the Qt Code of Conduct

                S 1 Reply Last reply
                0
                • kshegunovK kshegunov

                  @SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:

                  @jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.

                  Make your variables global then, what's the difference between a singleton and that ...? At least that way it looks and feels like C, while the singleton gives you a fake "object-oriented vibe". It's just plain C - a global variable with global functions.

                  S Offline
                  S Offline
                  SpartaWHY117
                  wrote on last edited by
                  #8

                  @kshegunov
                  for my current project, I create an core instance in main thread. And the in both another two threads , i also create instances . So , is that means every thread has it's own instance and data?

                  kshegunovK 1 Reply Last reply
                  0
                  • S SpartaWHY117

                    @kshegunov
                    for my current project, I create an core instance in main thread. And the in both another two threads , i also create instances . So , is that means every thread has it's own instance and data?

                    kshegunovK Offline
                    kshegunovK Offline
                    kshegunov
                    Moderators
                    wrote on last edited by
                    #9

                    @SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:

                    So , is that means every thread has it's own instance and data?

                    Yes, it's called reentrancy. You should try to ensure every thread works on its own data if possible.

                    Read and abide by the Qt Code of Conduct

                    S 1 Reply Last reply
                    0
                    • kshegunovK kshegunov

                      @SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:

                      So , is that means every thread has it's own instance and data?

                      Yes, it's called reentrancy. You should try to ensure every thread works on its own data if possible.

                      S Offline
                      S Offline
                      SpartaWHY117
                      wrote on last edited by
                      #10

                      @kshegunov actually i want to two threads to own the same instance which created in main thread. So i change the instance into QSharedPointer .

                      kshegunovK 1 Reply Last reply
                      0
                      • S SpartaWHY117

                        @kshegunov actually i want to two threads to own the same instance which created in main thread. So i change the instance into QSharedPointer .

                        kshegunovK Offline
                        kshegunovK Offline
                        kshegunov
                        Moderators
                        wrote on last edited by
                        #11

                        It's not that simple. If data is shared between threads, you have to synchronize them manually through a mutex or a semaphore. QSharedPointer as the name suggests, is a pointer that's being shared, not the object it points to.

                        Read and abide by the Qt Code of Conduct

                        1 Reply Last reply
                        1

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved