Qt和线程本地服务器,为什么整个UI卡住了?
这是一个最小的测试用例,我尝试使用 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
}
Here's a minimal test case , I tried to start a local domain server , with QThread
, so the UI shouldn't stuck. But when it's starting , i saw Listening
output from qDebug() , but the widgets added from form editor totally disappeared , everything went slow (e.g resizing the window) , if i remove thread.start()
, the UI shows up and functions well.
#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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
accept(2) 系统调用默认是阻塞的。您应该利用多路复用系统调用 poll(2) 或 select(2) 由 QApplication 的 exec 事件循环。
请参阅此问题并使用QtNetwork 模块。
The accept(2) syscall is by default blocking. You should take advantage of the multiplexing syscall poll(2) or select(2) used by the QApplication's exec event loop.
See this question and use the QtNetwork module.
首先,你的 setupServer 总是在 gui 线程中调用。提供您自己的基于 QThread 的类并重新实现 run 方法。将您的“setupServer”代码放入其中
First of all, your setupServer is always called in gui thread. Deliver your own QThread based class and reimplement run method. Put your "setupServer" code inside