Ajay
Ajay

Reputation: 10227

Which is a better usage of QMutexLocker and QMutex?

I was wondering which usage is better with respect to Mutex. The 2 usage which came to my mind are :

1)

   Qlist getList()
   {
      QMutexLocker locker(&m_mutex);
      return m_list;

   }

   for ( int i =0 ;i < getList.count ; i++)
   {
             obj = getList.at(i)
             //some work 
             //  on obj            
    }

2)

    Qlist getList()
    {
      return m_list;

   }

   {
     QMutexLocker locker(&m_mutex);
     for ( int i =0 ;i < getList.count ; i++)
     {
             obj = getList.at(i)<br>
             //some work 
             //  on obj                
     }
   }

In short, is it better to protect the list wherever it is being used or it is ok to put a mutex in the getlist function from where the list is being returned?

Upvotes: 0

Views: 3571

Answers (2)

Troubadour
Troubadour

Reputation: 13431

I don't understand why you would lock the mutex in the getter. All you are achieving there is preventing other protected sections from running whilst a QList shallow copy is made.

You need to lock the mutex whilst you are performing operations on the QList that need to be done in isolation from any other access to the QList. The nature of the work you do on the QList in the loop and how other threads may be interacting with it at the same time will dictate whether you need to lock it.

If no other thread can change the number of elements during the loop then it may be safe to lock only within the loop body around the work you do on each element (it still depends on what other threads may do with the contents of the QList), otherwise lock outside the loop body. Locking within just the getter achieves nothing.

Upvotes: 3

Paolo Brandoli
Paolo Brandoli

Reputation: 4750

Locking and unlocking could be an expensive operation, but locking a resource for a long time may prevent other threads to continue their work.

So, if some "work on obj" takes too long I would lock in SomeFuntion(), otherwise outside the for loop.

Having said that, I would also keep the design clean: this mean that if the part that have the for loop shouldn't be aware of the mutex (e.g. is in a different class) I would lock in SomeFunction regardless of the operation's length, or I would move the mutex somewhere else. Of course remember to document which method is thread safe and which one is not.

PS: From the code you posted it is quite difficult to understand if the two blocks are in the same class or not

Upvotes: 1

Related Questions