【问题标题】:Launch a server and an IHM in different thread在不同的线程中启动服务器和 IHM
【发布时间】:2014-06-26 09:12:46
【问题描述】:

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

我设计了一个带有按钮之类的 IHM:

这是我的main window

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

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

为此,我想我需要:THREAD AND SHARED MEMORY SEGMENTATION

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

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

//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();
    }
}

PROBLEM : 服务器启动但不是IHM,我不明白为什么,因为它应该在一个线程中......

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

谢谢。

【问题讨论】:

  • 你在 t1.join() 上被阻塞,它等待 t1 结束,然后离开你的构造函数
  • @jbh Ho 看起来不错,你有解决方案吗?因为我从线程的使用开始...
  • Belloiel:将线程存储在成员变量中,而不是堆栈中。让你的服务器线程去吧,在你真的想确保它自己结束之前不要加入
  • @jbh 谢谢,你能解释一下怎么做吗?因为我不明白我们如何将线程存储在成员变量中。另外,您如何看待共享内存分段?你可以发帖回答,我会接受的,谢谢你的帮助。

标签: c++ multithreading qt network-programming


【解决方案1】:

由于您的服务器读取线程是一个无限循环,您永远不会退出它。因此,对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);
}

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

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
}

【讨论】:

  • 你也可以有一个线程管理器对象或其他东西,这个答案比我的解释得更好。
  • @Mayerz:您建议更好地使用线程启动是正确的。此示例仅为设施提供。我不会从 UI 对象声明和启动守护线程。
  • 谢谢,所以如果我希望我的服务器线程在我关闭主窗口时停止,我应该在线程上调用什么函数?如果你说我做的不是最好的,我应该做的更好吗?
  • 在 std::thread 中没有可用的停止线程的方法。由于可用的同步机制或一旦其工作完成,您的线程必须自行停止。我建议您阅读有关该主题的一些内容。
  • 你可以在你的 IHM 线程中定义一个条件,关闭另一个线程,然后停止他自己的 exec 并返回主执行。
【解决方案2】:

std::thread::join() 阻塞当前线程,直到 t1 线程完成其执行。

您基本上将自己锁定在 t1 线程中。

怎么办?

将 t1 存储在其他地方,以便您稍后访问它,完成您对 ihm 线程所做的事情等。当一切就绪后,访问 t1 并调用 join()。

我看到了什么:

int main()
{
std::cout << "starting first thread...\n";
std::thread t1(foo);

std::cout << "starting second thread...\n";
std::thread t2(bar);

std::cout << "waiting for threads to finish..." << std::endl;
helper1.join();
helper2.join();

std::cout << "done!\n";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多