c++ - 在不同线程中启动服务器和 IHM

标签 c++ multithreading qt network-programming

我需要您对我正在编写的程序的建议。首先,让我向您介绍一下它是什么:

我设计了一个带有按钮和类似东西的 IHM:

这是我的主窗口: Main Window

当我点击 QButton Supervision 时,我将进入这个窗口: Supervision Window

IHM 完成后,我编写了一个服务器,它可以工作,并处理接收到的帧。现在我想做的是同时启动服务器和 IHM,当我点击监督时,在 QTableWidget 中显示服务器收到的信息。

为此,我认为我需要:THREADSHARED MEMORY SEGMENTATION

Thread:启动服务器和 IHM,以及 Memory Segmentation:将服务器接收到的数据提供给我的 IHM。

我尝试在我的主窗口的构造函数中启动服务器,这是我的主窗口中的代码:

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

    //Start my window (initialisation of button code
...
    //Thread of the server
    std::thread t1(lancerServeur);
    t1.join();


}
//Server function lauch by thread
void MainWindow::lancerServeur(){
Server s;
    while(1){
    s.readData();
    }
}

问题:服务器启动但 IHM 没有启动,我不明白为什么,因为它应该在线程中......

您还认为共享内存分段是个好主意吗?如果是,你有好的链接给我吗?

谢谢。

最佳答案

由于您的服务器读取线程是一个无限循环,您永远不会退出它。因此,对 join 的调用永远不会返回。将线程对象存储在成员变量中可确保一旦超出范围,它就不会被销毁。

//header file
#include <thread>

class MainWindow : public QMainWindow {
//...

private:
    std::thread m_t1;
};

//source file

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

    //Start my window (initialisation of button code
...
    //Thread of the server
    m_t1 = std::thread(lancerServeur);
}

如果您只想让一个线程自行运行而不关心它是否可连接,您也可以决定分离它。

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

    //Start my window (initialisation of button code
...
    //Thread of the server
    std::thread t1 = std::thread(lancerServeur);
    t1.detach();
    //..going out of scope will not destroy the thread
}

关于c++ - 在不同线程中启动服务器和 IHM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24426632/

相关文章:

C++预处理器#include

linux - 为什么在中断中使用 mutex_trylock 不安全?

c++ - 从辅助线程启动可执行文件

java - 客户端-服务器多线程

c++ - 如何在 QWidget 中获取 QtDataVizualisation 的 QPixmap 并保存到文件?

c++ - 如何根据给定的字符长度拆分 QString?

c++ - g++ 链接器问题

c++ - 预递增字符串文字

c++ - 大图像的 CUDA 内存分配问题

c++ - QNetworkCookieJar 中的 setCookiesFromUrl() 和 cookiesForUrl