Qt - Error when starting 5 threads from object array

I am making a application in Qt as my semester project. The topic is "Problem of dining philosophers". Now I have a problem and I don't really know how to solve it. The problem is: I have an array of objects called filozofowie (philisophers) and it contains objects of class filozof (philosopher). Class philospher is derived from class Thread. When I am trying to start threads from array in for loop, it's starting four of them and then error occurs.
Here's the error: https://i.sstatic.net/BqkdK.png

Here's the code:

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

Part of 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);
}

Please don't mind the text in append, those are messages in Polish.

Upvotes: 1

Views: 444

Answers (1)

hyde
hyde

Reputation: 62888

At least you have problem here:

Filozof filozofowie[4];

Indexes are 0..3, but here you have 0..4:

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

Also, your "if isRunning" is a bit funny. You maybe should connect the started signal, or use the waitForStarted method.

Upvotes: 2

Related Questions