2012-12-01 43 views
1

我在Qt中創建一個應用程序作爲我的學期項目。主題是「哲學家就餐問題」。現在我有一個問題,我不知道如何解決它。問題是:我有一個名爲filozofowie(philisophers)的對象數組,它包含類filozof(哲學家)的對象。 Class philospher來自Thread類。當我嘗試從for循環中的數組開始線程時,它將啓動它們中的四個,然後發生錯誤。
這裏的錯誤:http://i.imgur.com/D0i7T.pngQt - 從對象數組中啓動5個線程時出錯

下面的代碼:

Filozof.h

#ifndef FILOZOF_H 
#define FILOZOF_H 

#include <QtCore> 
#include <QtGui> 

class Filozof : public QThread 
{ 
    public: 
    Filozof(); 
    void run(); 
    QString name; 
    QLabel *stan; 
}; 

#endif 

Mainclass.h

#ifndef MAINCLASS_H 
#define MAINCLASS_H 

#include <QtGui> 
#include <QtCore> 
#include "ui_mainwindow.h" 
#include "Filozof.h" 

class MainClass : public QMainWindow 
{ 
    Q_OBJECT 

public: 
    MainClass(QWidget *parent = 0, Qt::WFlags flags = 0); 
    ~MainClass(); 
    Ui::MainClassClass ui; 
    Filozof filozofowie[4]; 
    QSystemSemaphore *kelner; 

public slots: 
    void startSimulation(); 
    void stopSimulation(); 
}; 

#endif // MAINCLASS_H 

部分mainclass.cpp

void MainClass::startSimulation() 
{ 
    this->kelner = new QSystemSemaphore("kelner", 4, QSystemSemaphore::Create); 
    ui.textEdit->append("[" + QDateTime::currentDateTime().toString() + "] Start  symulacji"); 
    for(int i = 0; i < 5; i++) 
    { 
     filozofowie[i].start(); 
     if(filozofowie[i].isRunning()) 
     { 
      ui.textEdit->append("[" + QDateTime::currentDateTime().toString() + "] Watek filozofa " + QString::number(i) + " wystartowal"); 
     }else{ 
      ui.textEdit->append("[" + QDateTime::currentDateTime().toString() + "] Blad podczas tworzenia watku filozofa " + QString::number(i)); 
     } 
    } 

    ui.buttonStart->setEnabled(false); 
    ui.buttonStop->setEnabled(true); 
} 

請不要介意附加的文字,這些是波蘭語的信息。

+0

請寫出問題中的錯誤,問題應該是獨立的,不依賴於其他網站。 – hyde

+0

@luketorjussen:請閱讀作業標籤wiki。 – Mat

回答

2

至少你有問題就在這裏:

Filozof filozofowie[4]; 

索引是0..3,但在這裏你有0..4:

for(int i = 0; i < 5; i++) 

而且,你的 「如果isRunning」 是有點有趣。你可能應該連接啓動的信號,或使用waitForStarted方法。

+0

謝謝你的回答,我已經找到了解決方案。這真的很明顯,但我有點不舒服(流感或某事),頭痛並沒有幫助。也感謝第二部分的迴應。我是QT新手,所以我不知道所有事情,但肯定會幫助:-)。 –

相關問題