Multithread in Qt

发布于 2022-08-07 00:19:23 字数 2896 浏览 8 评论 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文