【发布时间】:2014-06-26 14:00:38
【问题描述】:
我在我的班级MainWindow 中创建了一个启动server 的线程,当我关闭这个MainWindow 时,我需要停止该服务器,但我不能因为该服务器在while(true) loop 中运行。所以我看到的唯一可能就是杀死包含服务器的线程。
但这仍然不可能,因为我使用了#include <thread> 和C++11。
我的解决方案是将boolean 传递给我的服务器,并执行循环,而这个布尔值是真的。但是当我的布尔值变为假时,我无法退出循环,因为我的服务器等待接收在完成循环之前没有出现的帧。
这是我的代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//Some initialisation
...
// Constructs the new thread and runs it. Does not block execution.
m_t1 = std::thread(lancerServeur);
}
MainWindow::~MainWindow()
{
delete ui;
m_t1.join();
}
void MainWindow::lancerServeur(){
serveur s;
while(true){
s.receiveDataUDP();//Wait for a frame
}
}
那么,有没有办法在 C++11 中杀死我的线程,或者你有没有办法停止我的服务器?
谢谢。
【问题讨论】:
-
你不能,不是以安全或便携的方式。您可以让循环检查一些变量(可能是condition variable)并在设置时退出,而不是无限循环。
-
不是标准方式,不是。 C++11 断言线程需要相互协作;所以主线程需要通知子线程退出。我记得在他们将其添加到规范中时读到了这一点,它与整个程序的稳定性有关。如果线程从外部终止,它可能会使事物处于不确定状态。
-
@JoachimPileborg 我不能因为我的服务器等待一帧,然后暂停我的线程。
-
您需要修改
s.receiveDataUDP();,使其不会阻塞或使用事件。 -
@JohnnyMopp 我要等一帧,不等怎么办。
标签: c++ multithreading qt c++11 network-programming