2012-01-23 35 views
1

我是Qt的新手,我正在尋找Qt中的多線程。
正如我在Qt Documents瞭解到,我定義了兩個類兩個線程:我的多線程應用程序使用Qt有什麼問題(錯誤SIGSEGV)

#include <QThread> 
#include <QMutex> 

class thread_a : public QThread 
{ 
    Q_OBJECT 
public: 
    explicit thread_a(QObject *parent = 0); 
    int counter; 

protected: 
    void run(); 
}; 

和CPP文件:

#include "thread_a.h" 

thread_a::thread_a(QObject *parent) : 
    QThread(parent) 
{ 
    counter=0; 
} 

void thread_a::run() 
{ 
    counter++; 
} 

第二個線程類是相同的,但在run()方法counter--
然後,我從main.ccp運行這兩個線程。沒問題。但是當我在插槽上運行這兩個線程時,出現了問題。以「Signal Recived」爲標題的對話框稱爲「劣勢因爲它從操作系統收到信號而停止。信號名稱:SIGSEGV,信號含義:分段錯誤」

出現了什麼問題?

更新:
這是我的槽:

public slots: 
    void run_threads(bool); 

void MainWindow::run_threads(bool bl) 
{ 
    thread_a a; 
    thread_b b; 
    a.start(); 
    b.start(); 
} 

,我通過連接的按鈕來此插槽:

QObject::connect(ui->pushButton, SIGNAL(clicked(bool)), 
          this, SLOT(run_threads(bool))); 
+2

請張貼您使用「上槽運行兩個線程」的代碼。 – Mat

回答

2

你插槽創建你的線程的兩個實例班級,開始他們和出口。此時函數返回並且實例超出範圍,從而被破壞。您應該保留對這些實例的訪問權限,以便它們不被破壞並可能重用它們。

class MainWindow { 
//...other stuff 
    public slots: 
    void run_threads(bool); 
    private: 
    thread_a a; 
    thread_b b; 
//...other stuff 
}; 

void MainWindow::run_threads(bool bl) 
{ 
    if(!a.isRunning()) 
    a.start(); 

    if(!b.isRunning()) 
    b.start(); 
} 
+0

是啊!這樣可行。謝謝@DustyCampbell –

相關問題