如何从另一个线程停止 运行 线程?

How to stop a running thread from another thread?

我想放置一个停止按钮来停止除主线程之外的所有线程。为此,编写了如下代码:

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

现在,当我按下开始按钮时一切正常 good.But,当我按下开始按钮并按下停止按钮时 function1 为 运行,程序崩溃。

如果我使用休眠函数而不是退出函数,首先函数 1 结束,然后休眠函数开始。

当子线程工作时我必须做些什么来停止它们。我的意思是我不想等待他们的过程。想停下来

如果您正忙于在重新实现的线程中循环,您应该使用 QThread::isInterruptionRequested() 跳出循环并立即从 run() 函数中 return:

void serialclass::function1() {
  while (! thread()->isInterruptionRequested())
    msleep(10);
}

如果您按原样为其事件循环使用 QThread,则需要调用其 quit() 方法。

分解:

void stop(QThread * thread) {
  thread->requestInterruption();
  thread->quit();
}

你在 function1() 中所做的是错误的。你不应该那样阻塞线程。您正在以伪同步方式编写代码。反转控制流以始终在事件循环中保持控制,然后 QThread::quit() 将按预期工作。