【发布时间】:2023-10-03 04:41:01
【问题描述】:
我想放一个停止按钮来停止除主线程之外的所有线程。为此,编写了如下代码:
serialclass *obje = new serialclass();
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QThread *thread = new QThread();
obje->moveToThread(thread);
connect(this,SIGNAL(signal_stop()),obje,SLOT(stop_thread()),Qt::UniqueConnection);
thread->start();
}
void MainWindow::on_pushButton_baslat_clicked() //başlat butonu
{
connect(this,SIGNAL(signal()),obje,SLOT(function1()), Qt::UniqueConnection);
emit signal();
}
void MainWindow::on_pushButton_stop_clicked()
{
qDebug()<<QThread::currentThreadId()<<"=current thread(main thread)";
emit signal_stop();
}
在 SerialClass 部分:
void serialclass::function1()
{
int i;
for(i=0;i<99999;i++)
{
qDebug()<<i;
}
}
void serialclass::stop_thread()
{
qDebug()<<QThread::currentThreadId()<<"Serial thread";
QThread::currentThread()->exit();
}
现在,当我按下启动按钮时,一切正常。但是,当我按下启动按钮并在功能 1 运行时按下停止按钮时,程序崩溃。
如果我使用睡眠功能而不是退出,首先 function1 结束,然后睡眠功能开始。
当子线程工作时我必须做些什么来停止子线程。我的意思是我不想等待他们的过程。想停下来
【问题讨论】:
-
您有一些
processEvents调用还是在function1中使用本地事件循环? -
我编辑了function1。让我们说这样的话。 99999 显示后,stop_threads 正在调用
-
其实我不知道什么是事件进程或事件循环。
-
感谢您的评论我把 qApp->processEvents();它有效:)
-
不要那样做。这是自找麻烦。
标签: multithreading qt signals-slots qthread