Reputation: 3258
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.
Upvotes: 4
Views: 4662
Reputation: 6823
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
QMutex mutex;
void someMethod()
{
mutex.lock();
// Critical section
mutex.unlock();
}
Now, lock
and unlock
are 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 the lock(...) { ... }
block is replaced by mutex.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 QMutex
here: http://doc.qt.io/qt-4.8/qmutex.html
Upvotes: 2
Reputation: 40750
The general C++ way to do things like this is using RAII, so you wind up with code like this:
// 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
}
I don't know how that translates to Qt, but you could probably write a helper class if there's no native support.
EDIT: Thanks to Cory, you can see that Qt supports this idiom very nicely.
Upvotes: 2
Reputation: 16373
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 RAII idiom - the lock guard is an object that will release the lock no matter how someMethod scope is exited (normal return or throw). See C++ concurrency In Action by Anthony Williams. He also has a C++11 thread implementation. The C++11 implementation is much like the boost thread implementation.
Upvotes: 0