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 use QMutex to lock on other thread when passing by pointer?

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

Scheduled Pinned Locked Moved General and Desktop
5 Posts 2 Posters 1.6k 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.
  • A Offline
    A Offline
    Arrandale
    wrote on last edited by
    #1

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

    1 Reply Last reply
    0
    • sierdzioS Offline
      sierdzioS Offline
      sierdzio
      Moderators
      wrote on last edited by
      #2

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

      (Z(:^

      1 Reply Last reply
      0
      • A Offline
        A Offline
        Arrandale
        wrote on last edited by
        #3

        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.

        1 Reply Last reply
        0
        • sierdzioS Offline
          sierdzioS Offline
          sierdzio
          Moderators
          wrote on last edited by
          #4

          Not a requirement, just my preference.

          (Z(:^

          1 Reply Last reply
          0
          • A Offline
            A Offline
            Arrandale
            wrote on last edited by
            #5

            OK.
            Thanks a lot.

            1 Reply Last reply
            0

            • Login

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