1

先日QThreadを試していて、for、foreach、whileではなくシグナルのみを使用して無限ループを作成したかったのですが、シグナルを発行してスロットを何度も実行した後にコードがクラッシュしました。私のコードは次のとおりです。

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "worker.h"
#include <QThread>
#include <QDebug>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void startthreads();

private:
    Ui::MainWindow *ui;
    QThread thread;
    worker *work;

};

#endif // MAINWINDOW_H

//worker.h
#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QDebug>
#include <QMutex>
#include "insiderobject.h"

class worker : public QObject
{
    Q_OBJECT
public:
    explicit worker(QObject *parent = 0);

signals:
    void doagain();
    void okidid();
    void finished();

public slots:
    void printing();
};

#endif // WORKER_H

//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    startthreads();
}

MainWindow::~MainWindow()
{
    thread.wait();
    delete ui;
    delete work;
}

void MainWindow::startthreads()
{
    work = new worker;
    work->moveToThread(&thread);
    connect(&thread, SIGNAL(started()), work, SLOT(printing()));
    connect(work, SIGNAL(finished()), &thread, SLOT(quit()));
    thread.start();
}

//worker.cpp
#include "worker.h"

worker::worker(QObject *parent) :
    QObject(parent)
{
    connect(this, SIGNAL(okidid()), this, SLOT(printing()));
}

void worker::printing()
{
    qDebug() << "printing";
    emit okidid();
}

//main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

シグナル/スロット、スレッド、キュー接続、または手に入れることができるものについてのドキュメント全体を読みましたが、このクラッシュの理由を理解できませんでした...また、Qt ircチャットルームで人々や開発者とチャットしようとしましたが、誰も理由を教えてくれませんでした。

4

1 に答える 1