免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4676 | 回复: 0
打印 上一主题 下一主题

Multithread in Qt [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-01-15 00:15 |只看该作者 |倒序浏览
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.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP