• 7040阅读
  • 2回复

Multithread in Qt [复制链接]

上一主题 下一主题
离线xizhizhu
 
只看楼主 倒序阅读 楼主  发表于: 2009-01-15
— 本帖被 XChinux 从 General Qt Programming 移动到本区(2011-01-02) —
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.
http://xizhizhu.blogspot.com
离线wu9961

只看该作者 1楼 发表于: 2009-01-15
这里是Qt中文论坛........
离线xizhizhu
只看该作者 2楼 发表于: 2009-01-15
俺懒,最近只写英文blog了,所以嘛~~~~
http://xizhizhu.blogspot.com
快速回复
限100 字节
 
上一个 下一个