c++ - 这是使用 QThread 的正确方法吗?

标签 c++ qt qthread

我正在查看一些 github 项目,其中一个项目通过以下方式进行了 UDP 链接, 首先它继承 QThread 创建一个类 UDPLink:public QThread 它的构造函数和析构函数如下:

UDPLink::UDPLink(UDPConfiguration* config)
    : _socket(NULL)
    , _connectState(false)
{
    Q_ASSERT(config != NULL);
    _config = config;
    _config->setLink(this);

    // We're doing it wrong - because the Qt folks got the API wrong:
    // http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
    moveToThread(this);

    // Set unique ID and add link to the list of links
    _id = getNextLinkId();
    qDebug() << "UDP Created " << _config->name();
}

UDPLink::~UDPLink()
{
    // Disconnect link from configuration
    _config->setLink(NULL);
    _disconnect();
    // Tell the thread to exit
    quit();
    // Wait for it to exit
    wait();
    this->deleteLater();
}

虽然代码确实可以编译和运行,但我想知道这种使用 QThread 的方式是否正确?

最佳答案

QThread 的 Qt 文档描述了使用 QThread 完成线程化的两种方式。子类化 QThread 是最初使用 QThread 的唯一方法。要以这种方式使用 QThread,请覆盖 run 方法,该方法是在新线程上运行的 QThread 方法。 QThread 应该被认为是一个线程管理器,而不是一个运行在单独线程本身上的对象。来自文档:

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.

When subclassing QThread, keep in mind that the constructor executes in the old thread while run() executes in the new thread. If a member variable is accessed from both functions, then the variable is accessed from two different threads. Check that it is safe to do so.

QThread documentation page

正是因为QThread是一个线程管理器类,才产生了将对象移动到线程的解决方案。您提供的代码中的注释对这一更改做出了声明,因为那篇文章指出 moveToThread(this) 不是一个好的做法。

创建对象并将其移动到线程和子类化 QThread 都是使用 Qt 进行线程化的有效方法,正如文档现在明确指出的那样。如果您希望跨线程边界使用信号/槽连接,则使用工作对象方法有一个好处:工作对象将在它移动到的线程上有可用的槽。

关于c++ - 这是使用 QThread 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29023790/

相关文章:

c++ - Mac 中带有 qt 的 DCMTK 库

javascript - 在 QML 中使用对话框

c++ - Qt, C++, 如何退出 QThread

c++ - Qt多线程启动线程报错

c++ - QReadWriteLock 递归模式不起作用

c++ - 如何在图像中绘制一个矩形,只有当鼠标移动到opencv中的特定位置时才会显示?

c++ - 不能使用 SDL 线程

c++ - 为什么有人会使用 C 而不是 C++?

c++ - MSVC6 : Breakpoint stops program

c++ - Qt : Create a Stack of image