Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7166769
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T14:28:00+00:00 2026-05-28T14:28:00+00:00

I’m newbie to Qt and I’m looking for multi-threading in Qt. As I learned

  • 0

I’m newbie to Qt and I’m looking for multi-threading in Qt.
As I learned in Qt Documents, I defined two class for two thread:

#include <QThread>
#include <QMutex>

class thread_a : public QThread
{
    Q_OBJECT
public:
    explicit thread_a(QObject *parent = 0);
    int counter;

protected:
    void run();
};

And in CPP file:

#include "thread_a.h"

thread_a::thread_a(QObject *parent) :
    QThread(parent)
{
    counter=0;
}

void thread_a::run()
{
    counter++;
}

Second thread class is same, but with counter-- in run() method.
Then I run this two threads from main.ccp.

Now my question:
How can I share counter in thread_a and thread_b using QMutex?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T14:28:01+00:00Added an answer on May 28, 2026 at 2:28 pm

    Instead of having the data within a thread, move the data outside the thread, protect it and then access it from both threads.

    The following is a sketch, of what you could do:

    class Counter
    {
      public:
        Counter():mMutex(),mCounter(0){}
        int inc()
        {
          QMutexLocker ml(&mMutex);
          return mCounter++;
        }
        int dec()
          QMutexLocker ml(&mMutex);
          return mCounter--;
        }
      private:
        QMutex mMutex;
        int mCounter;
        Q_DISABLE_COPY(Counter)
    };
    
    class ThreadA : public QThread
    {
      public:
        ThreadA(Counter* ctr);
      /* ... */
    };
    
    class ThreadB : public QThread
    {
      public:
        ThreadB(Counter* ctr);
      /* ... */
    };
    

    The construct of Counter is often referred to as a Monitor, from Wikipedia (emphasis mine):

    In concurrent programming, a monitor is an object or module intended to be used safely by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion. That is, at each point in time, at most one thread may be executing any of its methods. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared to reasoning about parallel code that updates a data structure.

    In this specific case, a more efficient construct would be QAtomicInt.
    This gains atomicity from its use of special CPU instructions.
    This is a low level class that could be used to implement other threading constructs.


    Edit – Complete Example

    Using threads with shared state correctly is not trivial. You may want to consider using Qt signals/slots with queued connections or other message based systems.

    Alternatively, other programming languages such as Ada support Threads and Monitors (protected objects) as native constructs.

    Here is a complete working example.
    This is only sample code, don’t use QTest::qSleep in real code.

    objs.h

    #ifndef OBJS_H
    #define OBJS_H
    
    #include <QtCore>
    
    class Counter
    {
        public:
            Counter(int init);
            int add(int v);
        private:
            QMutex mMutex;
            int mCounter;
            Q_DISABLE_COPY(Counter)
    };
    
    class CtrThread : public QThread
    {
        Q_OBJECT
        public:
            CtrThread(Counter& c, int v);
            void stop();
        protected:
            virtual void run();
        private:
            bool keeprunning();
            Counter& mCtr;
            int mValue;
            bool mStop;
            QMutex mMutex;
    };
    
    #endif
    

    objs.cpp

    #include "objs.h"
    
    Counter::Counter(int i):
        mMutex(),
        mCounter(i)
    {}
    
    int Counter::add(int v)
    {
        QMutexLocker ml(&mMutex);
        return mCounter += v;
    }
    
    ///////////////////////////////////////
    
    CtrThread::CtrThread(Counter& c, int v):
        mCtr(c),
        mValue(v),
        mStop(false),
        mMutex()
    {}
    
    void CtrThread::stop()
    {
        QMutexLocker ml(&mMutex);
        mStop = true;
    }
    
    void CtrThread::run()
    {
        while(keeprunning())
        {
            mCtr.add(mValue);
        }
    }
    
    bool CtrThread::keeprunning()
    {
        QMutexLocker ml(&mMutex);
        return ! mStop;
    }
    

    test.cpp

    #include <QtCore>
    #include <QTest>
    #include "objs.h"
    
    int main(int argc, char** argv)
    {
        QCoreApplication app(argc, argv);
    
        qDebug() << "Initalising";
    
        Counter ctr(0);
        CtrThread thread_a(ctr, +1);
        CtrThread thread_b(ctr, -1);
    
        qDebug() << "Starting Threads";
    
        thread_a.start();
        thread_b.start();
    
        for (int i = 0; i != 15; ++i)
        {
            qDebug() << "Counter value" << ctr.add(0);
            QTest::qSleep(1000);
        }
    
        qDebug() << "Stopping Threads";
    
        thread_a.stop();
        thread_b.stop();
        thread_a.wait();
        thread_b.wait();
    
        qDebug() << "Finished";
        return 0;
    }
    

    test.pro

    QT=core testlib
    HEADERS=objs.h
    SOURCES=test.cpp objs.cpp
    

    Compile and run, you will see the value being printed, sample output:

    Initalising
    Starting Threads
    Counter value 0
    Counter value 11057
    Counter value 28697
    Counter value 50170
    Counter value 60678
    Counter value 73773
    Counter value 84898
    Counter value 96441
    Counter value 118795
    Counter value 135293
    Counter value 146107
    Counter value 158688
    Counter value 169886
    Counter value 201203
    Counter value 212983
    Stopping Threads
    Finished
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I've tracked down a weird MySQL problem to the two different ways I was
I have a reasonable size flat file database of text documents mostly saved in
I am trying to loop through a bunch of documents I have to put
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.