【问题标题】:Qt and threaded local server , why is the whole UI stuck?Qt 和线程本地服务器,为什么整个 UI 卡住了?
【发布时间】:2012-01-06 13:31:47
【问题描述】:

这是一个最小的测试用例,我尝试使用 QThread 启动本地域服务器,因此 UI 不应该卡住。但是当它开始时,我看到了来自 qDebug() 的Listening 输出,但是从表单编辑器添加的小部件完全消失了,一切都变慢了(例如调整窗口大小),如果我删除thread.start(),UI 会显示出来并且运行良好.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect (&thread , SIGNAL(started()) , SLOT(setupServer()));
    thread.start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupServer()
{
    struct sockaddr_un address;
    int socket_fd, connection_fd;
    socklen_t address_length;

    // create socket .. and create socket file ..
    // bind ...
    // listen ..

    qDebug() << "Listening ..";

    while((connection_fd = ::accept(socket_fd,
                                    (struct sockaddr *) &address,
                                    &address_length)) > -1)
    {
        qDebug() << "Got an connection.";
        ::close (connection_fd);
    }

    // close socket and remove the socket file
}

【问题讨论】:

    标签: sockets unix networking qt4 qthread


    【解决方案1】:

    accept(2) 系统调用默认是阻塞的。您应该利用 QApplication 的 exec 事件循环使用的多路复用系统调用 poll(2)select(2)

    查看this question 并使用QtNetwork 模块。

    【讨论】:

      【解决方案2】:

      首先,您的 setupServer 总是在 gui 线程中调用。交付您自己的基于 QThread 的类并重新实现 run 方法。把你的“setupServer”代码放进去

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 2019-10-16
        • 1970-01-01
        相关资源
        最近更新 更多