C++ 工人/控制器多线程和接口类

C++ 工人/控制器多线程和接口类,c++,multithreading,qt,interface,qthread,C++,Multithreading,Qt,Interface,Qthread,在我看来,它实现了一个多线程对象的接口类。当窗口关闭时,除这一行外,所有操作都正常 connect(_controller, &IClass::finished, this, [] { qDebug() << "finished"; }); mainwindow.cpp 不要发出关于问题2的已完成的:尝试对您的主进行此编辑: #include "mainwindow.h" #include <QApplication> int main(

在我看来,它实现了一个多线程对象的接口类。当窗口关闭时,除这一行外,所有操作都正常

connect(_controller, &IClass::finished, this, [] { qDebug() << "finished"; });

mainwindow.cpp 不要发出关于问题2的
已完成的
:尝试对您的
进行此编辑:

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

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

    int r = a.exec();

    qDebug() << "event loop gone ...";

    return r;
}
通过这种方式,您可以退出应用程序,但只有在所有排队事件得到处理(即排队信号得到传递…)后才能退出


坦白地说,关于你问的所有其他问题:即使是一个悬赏问题,它似乎也相当宽泛。无论如何,希望我能帮点忙。

也许我忽略了它,你在哪里“转发”并从你的IClass发出完成的()信号?点击按钮调用
,然后工作,但我不明白,为什么
控制器::~Controller(){u signals.callStop();QCoreApplication::processEvents();}
不工作。如果我只调用析构函数
MainWindow
,而不是
qApp->exit(),为什么主线程没有事件循环。为什么析构函数完成,而不执行
processEvent
?当调用析构函数时,事件循环已经消失,对processEvents的后续调用不再有意义。无论何时关闭(甚至隐藏)qt应用程序中的最后一个顶级小部件,事件循环都会自动停止,而无需调用
exit
。请记住,当
MainWindow
实例超出范围时,即退出
main
函数块时,
Qapplication::exec
返回后,会调用
MainWindow
析构函数。
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _controller(new Controller(IClass::Types::Worker2, this))
{
    ui->setupUi(this);
    connect(_controller, &IClass::started, this, [] { qDebug() << "started"; });
    connect(_controller, &IClass::finished, this, [] { qDebug() << "finished"; });
    _controller->start();
    _controller->f1();
    _controller->f2(2);
    _controller->f3(3, 4.4);
//    _controller->stop();
}

MainWindow::~MainWindow() { delete ui; }

PrivateController::~PrivateController() { qDebug() << "~PrivateController()"; }

IClass *IClass::CreateInstance(IClass::Types t, QObject *parent) {
    switch(t) {
    case Types::Worker1: { return new Worker1(parent); }
    case Types::Worker2: { return new Worker2(parent); }
    }
}

Controller::~Controller() { _signals.callStop(); }
Controller::start
Worker2::start
Worker2::f1
Worker2::f2 2
Worker2::f3 3 4.4
started
~PrivateController()
Worker2::stop
#include "mainwindow.h"
#include <QApplication>

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

    int r = a.exec();

    qDebug() << "event loop gone ...";

    return r;
}
void MainWindow::on_pushButton_clicked()
{
    _controller->stop();
    qApp->processEvents();
    qApp->exit();
}