I'm newbie to Qt and I'm looking for multi-threading in Qt.
As I learned in Qt Documents, I defined two class for two thread:
#include <QThread>
#include <QMutex>
class thread_a : public QThread
{
Q_OBJECT
public:
explicit thread_a(QObject *parent = 0);
int counter;
protected:
void run();
};
And in CPP file:
#include "thread_a.h"
thread_a::thread_a(QObject *parent) :
QThread(parent)
{
counter=0;
}
void thread_a::run()
{
counter++;
}
Second thread class is same, but with counter--
in run()
method.
Then I run this two threads from main.ccp
.
Now my question:
How can I share counter
in thread_a
and thread_b
using QMutex
?
Instead of having the data within a thread, move the data outside the thread, protect it and then access it from both threads.
The following is a sketch, of what you could do:
The construct of
Counter
is often referred to as a Monitor, from Wikipedia (emphasis mine):In this specific case, a more efficient construct would be
QAtomicInt
. This gains atomicity from its use of special CPU instructions. This is a low level class that could be used to implement other threading constructs.Edit - Complete Example
Using threads with shared state correctly is not trivial. You may want to consider using Qt signals/slots with queued connections or other message based systems.
Alternatively, other programming languages such as Ada support Threads and Monitors (protected objects) as native constructs.
Here is a complete working example. This is only sample code, don't use
QTest::qSleep
in real code.objs.h
objs.cpp
test.cpp
test.pro
Compile and run, you will see the value being printed, sample output: