- 论坛徽章:
- 0
|
http://xizhizhu.blogspot.com/2009/01/qt-development-viii-multi-thread.html
Threads should be subclasses of QThread, and the QThread.run() should be overrided, the code of which will be executed in a separate thread when calling QThread.start(). A thread ends when the QThread.run() ends, or QThread.terminate() is called. Following code shows the basic idea of two threads running concurrently.
// my thread
#include <QThread>
#include <iostream>
using namespace std;
class Thread: public QThread
{
Q_OBJECT
public:
Thread(int id, QObject* parent = NULL): QThread(parent)
{
this->id = id;
}
protected:
void run()
{
for (int i = 0; i < 10; i++)
{
cout << "Thread (" << id << ", " << i << ") before sleep" << endl;
QThread::msleep(10);
cout << "Thread (" << id << ", " << i << ") after sleep" << endl;
}
}
private:
int id;
};
// client code
include "thread.h"
#include <QApplication>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Thread thread1(1);
Thread thread2(2);
thread1.start();
thread2.start();
return app.exec();
}
If one object can be accessed by 2 or more threads, special attention should be paid that the object might be modified by one thread while another is using it, the result of which is always undefined. However, it might be quite difficult to detect such a problem, because the first time it appears may be months or even years after the creation of the process.
Qt has provided us with several ways to solve the problem, the easiest of which is to use QMutex. Calling QMutex.lock() makes the mutex object locked, or the function is blocked, if the mutex object is already locked, untill QMutex.unlock() is called. The QReadWriteLock is similar to QMutex, but it can distinguash between read and write operations, which makes the program more convenient. However, both QMutex and QReadWriteLock can only apply to the case where there is at most one instance of resource available. What if there are 2 or more instances of resource? QSemaphore provides us the solution. |
|