简体   繁体   中英

Qt-Using signals and slots with different threads

I'm still struggling to get this working as I expect.

I have a Qt project which I would like to update depending on signal states from different threads. My main GUI thread should start a worker thread running on the press of a start button.

The worker thread should then execute a function which continuously polls variables belonging to another class which are being updated by even a different thread (I am using portaudio libraries). It should then fire a signal (sendNewSig) which is connected to a slot (DrawData) in my GUI class.

The problem is the program crashes when I press my start button. I believe that I am missing some vital steps to start executing the worker thread. By calling updater->PollSignal() like this when the start button is clicked, I am expecting it to run in a new thread but perhaps not. I have shown parts of the code below which hopefully is enough to get my idea across.

Many thanks in advance for any help

In GUIApp.cpp

AudioGuiApplication::AudioGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
    ui.setupUi(this);

    //......  other stuff

    thread = new QThread(this);
    updater = new GUIUpdater(&audio_processor);
    updater->moveToThread(thread);

    connect(updater, SIGNAL(sendNewSig(string)), this, SLOT(DrawData(string)));

    connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));

    actionText->setPlainText("Press Start to begin ");
}

void AudioGuiApplication::on_startButton_clicked()
{
    updater->PollSignal();
}

In GUIUpdater.cpp`

void GUIUpdater::PollSignal() 
{ 
    string str;

    while (!ap->IsNewDataFound() )
    {
        emit sendNewSig(str);
        ap->SetNewSigFound(false);
    }
}`

You are calling the PollSignal function from the main/gui thread directly.

I think the easiest way to execute it in the desired thread is to employ the Signal & Slot mechanism with a single-shot QTimer set at no delay ( 0 stands for 0 milliseconds):

void AudioGuiApplication::on_startButton_clicked()
{
    QTimer::singleShot(0, updater, &GUIUpdater::PollSignal);
}

By the way: you should consider moving to the "new" connect syntax that doesn't rely on macros and allows compile-time type validation instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM