Lock objects in Qt like C #

in C # if I have a list that I could do

lock (this.mylist)
{
    ...
}

and with this code, I'm sure no one else can use this list before releasing the lock. This is useful in multi-threaded applications. How can I do the same on Qt? I read the docs about QMutex and QReadWriteLock, but I don’t understand how to use them on a particular object.

+3
source share
3 answers

QMutex ( C/++), , , . ( ++, - ) , mutex ( , ).

,

QMutex mutex;

void someMethod()
{
  mutex.lock();
  // Critical section
  mutex.unlock();
}

lock unlock , . , .

, , , C#, , . , lock(...) { ... } mutex.lock() ... mutex.unlock(). , , , (.. , this->mylist), .

Qt . QMutex : http://doc.qt.io/qt-4.8/qmutex.html

+1

++ - RAII, :

// Inside a function, a block that needs to be locked
{
  QMutexLocker lock(&mutex); // locks mutex
  // Do stuff

  // "QMutexLocker" destructor unlocks the mutex when it goes out of scope
}

, Qt, , , , .

EDIT: Cory , Qt .

+2

In C ++ 11, you can do this:

#include <thread>
#include <mutex>

std::mutex mut;

void someMethod()
{
  std::lock_guard(mut);
  // Critical section
}

This is the idiom of RAII - the lock protector - this is an object that will release the lock no matter how someMethod is displayed (normal return or throw). See C ++ concurrency In action by Anthony Williams. It also has a C ++ 11 thread implementation . The C ++ 11 implementation is very similar to the accelerated stream implementation.

0
source

All Articles