专门用于无限循环的QThread

时间:2019-03-13 21:41:31

标签: c++ qt

所以我想为我的无限while循环创建一个分离的线程。如何修复下面的代码,以免破坏信号插槽的连接?

#include "gameloop.h"

GameLoop::GameLoop(QObject *parent) : QObject(parent)
{
    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(mySlot()));
    timer->start(500);
    thread = new QThread();
    console = new Console;
    console->moveToThread(thread);
    thread->start();

    run();
}

GameLoop::~GameLoop()
{
    std::cout << "GameLoop() Destructor" << "\n";
}

void GameLoop::run()
{
     console->loop();
}



void GameLoop::mySlot()
{
    std::cout << "mySlot" << "\n";
}

控制台类中的成员函数loop()包含while(1)。

1 个答案:

答案 0 :(得分:0)

解决我的问题的解决方案如下代码所示,这种方式使无限循环位于专用于它的线程中:

#include "gameloop.h"
#include <QThread>
GameLoop::GameLoop(QObject *parent) : QObject(parent)
{
    std::cout << "GameLoop thread: " << QThread::currentThreadId()  << "\n";
    timer = new QTimer;
    timer->start(3000);
    connect(timer, SIGNAL(timeout()), this, SLOT(mySlot())); //timers

    thread1 = new QThread;

    console.moveToThread(thread1);
    thread1->start();
    connect(thread1, SIGNAL(started()), &console, SLOT(mySlotActivationLoop()));
}