2016-08-22 118 views
0

我想放置一個停止按鈕來停止除主線程以外的所有線程。爲了做到這碼像初級講座已被寫入:如何從另一個線程停止正在運行的線程?

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

現在,當我按下開始按鈕寄託都工作好。不過,當我按下啓動按鈕和我在function1運行時按下停止按鈕,程序崩潰。

如果我使用睡眠功能而不是退出,首先function1結束,然後睡眠功能啓動。

當他們工作時,我必須做些什麼來阻止子線程。我的意思是我不想等待他們的過程。只想停止

+0

你有'processEvents'調用,或者你在'function1'中使用本地事件循環嗎? – thuga

+0

我編輯了function1。讓我們說這樣的話。在99999顯示之後,stop_threads調用了 –

+0

其實我不知道eventprocess或event loop是什麼。 –

回答

0

如果你忙循環中重新實現線程,你應該使用QThread::isInterruptionRequested()打出來的循環,並立即從run()函數返回:如果您使用的是

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

QThread原因是它的事件循環,你需要調用它的quit()方法。

要因素吧:

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

你在做什麼在function1()是錯誤的。你不應該以這種方式阻止線程。您正在使用僞同步樣式編寫代碼。反轉控制流程以始終保持事件循環中的控制權,然後QThread::quit()將按預期工作。

+0

這種方法很有用,謝謝你的回覆,但我想問另一個問題。如何在requestinterruption()函數後繼續線程?啓動功能不起作用。 –

+0

您需要另外提問。 'start()'通常起作用:) –

+0

是的start()函數起作用。我犯了一個錯誤。謝謝 :) –

相關問題