in C# if I have for example a list I could do
lock (this.mylist)
{
...
}
and with that code I’m sure noone else can use the list before releasing the lock. This is useful in multithreaded applications. How can I do the same thing on Qt? I read docs about QMutex and QReadWriteLock but I don’t understand how to use them on a specific object.
To use
QMutex(or any standard synchronization method in C/C++) all critical sections which rely on each other must know about the mutex. The simplest (yet, not best practice in C++ i.e. make it a class member or something) way to ensure this, is to create a global variable mutex (which we will do for example).So consider the following
Now,
lockandunlockare atomic methods, so only one thread will be able to enter the critical section at any given time. The key is that both are trying to access the same mutex.So in essence, this works the same way as
C#except you need to manage your mutex yourself. So thelock(...) { ... }block is replaced bymutex.lock() ... mutex.unlock(). This also implies, however, that anytime you want to access the critical section items (i.e. in your example,this->mylist), you should be using the mutex.EDIT
Qt has very good documentation. You can read more about
QMutexhere: http://doc.qt.io/qt-4.8/qmutex.html