Domanda

I have a class, audio_engine_interface, and in main.cpp, I add it to the QML thing.

viewer.rootContext()->setContextProperty("engine", engine);

In audio_engine_interface, I have a audio_engine class, which is computationally intensive—it needs to run on its own thread.

void audio_engine_interface::play()
{
    QThread thread;
    thread.start();

    engine->moveToThread(&thread);

    engine->play(); // Will use 100% of CPU
}

However, when I do this, the whole QML thread locks up, meaning I can't pause (pretty important). Am I missing something?

EDIT: This thread won't mess up anything or access objects from other places. However, it does have a pause function that will need to be called at some point. For what it's worth, the engine is doing pitch shifting.

È stato utile?

Soluzione

This is a problem: -

Qthread thread;

Creating a QThread object like this is creating it on the stack. When the function ends, the object will go out of scope and delete the QThread object.

You need to dynamically allocate the object on the heap: -

QThread* thread = new QThread;

Then remember to delete the thread, or set it to delete itself: -

//Qt 5 connect syntax
connect(thread, &QThread::finished, thread, &QThread::deleteLater);

You should also be aware of thread affinity (the thread which an object is running on). I suggest reading this article on how to use QThread properly.

Altri suggerimenti

You have so many problems.

  1. when you move to thread your object must not have a parent
  2. your thread object is local variable so it will day immediately when udio_engine_interface::play() end execution
  3. you are invoking you engine->play(); method directly and this means that it will be executed in current thread.

moveToThread means that slots invked by signals connected using default 5th parameter (Qt::AutoConnection) will be queued in event loop of given thread.

The easiest way to fix it is use QtConcurrent:

void audio_engine_interface::play()
{
    QtConcurrent::run(engine, &EngineClass::play);
}

Depending what your engine does you should make it thread safe (use mutex locks an so on), without details it is hard to tell, what exactly you should do.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top