Please nominate your Qt Champions for 2021! https://forum.qt.io/topic/132134/looking-for-the-2021-qt-champions

How to use QMutex to lock on other thread when passing by pointer?



  • @class MyData
    {
    int number;
    };

    MyData myData;

    class MyThread1
    {
    public:

    void add(MyData *myData)
    {
    myData->number = 20;
    }
    };

    class MyThread2
    {
    public:

    void add(MyData *myData)
    {
    myData->number = 30;
    }
    };@

    How to lock "int number" on MyData;


  • Moderators

    @
    class MyData
    {
    public:
    void setNumber(int newValue)
    {
    QMutexLocker locker(&mutex);
    number = newValue;
    }

    protected:
    int number;
    QMutex mutex;
    };
    @

    Done :-)

    Althoug I wouild recommend using Qt::QueuedConnection and signals and slots, if possible. This way you avoid locking altogether.



  • Hmm...
    While I waiting the answer, I try to do this way, it's look like this but
    the difference is I declare QMutex on public and "int number" on private

    Any reason to declare both number and mutex on protected? Or it's must?

    Thanks.


  • Moderators

    Not a requirement, just my preference.



  • OK.
    Thanks a lot.


Log in to reply