暂停和恢复 QThread [英] Pause and Resume a QThread

查看:79
本文介绍了暂停和恢复 QThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习 QThreads,我有一个程序在一个单独的线程中运行 4 小时长的循环(以便我可以继续使用 GUI).我所追求的是,​​当用户单击暂停 qpushbutton 时会暂停/挂起线程,当用户单击恢复 qpushbutton 时,程序应该恢复.我怎样才能做到这一点?

I've recently began learning about QThreads and I've a program which runs a 4 hours long loop in a separate thread (so that I may continue to use the GUI). What I am after is, something that will pause/suspend the thread when the user clicks pause qpushbutton, and when the user clicks the resume qpushbutton, the program should resume. How may I achieve this?

我正在考虑从我的主要班级发送信号;但是,我不确定如何在线程中处理它们.是否可以在线程中处理从主类发送的信号?目前,我有线程向主类发送信号,并且工作正常,但我不确定如何从主类发送线程并在线程中接收它们.

I was thinking of sending signals from my main class; however, I'm not sure how I can handle them in the thread. Is it possible to handle signals sent from the main class in a thread? Currently, I have the thread emitting signals to the main class, and that works fine, but I'm not sure how to go about sending threads from the main class, and receiving them in the thread.

推荐答案

好的,所以我建议你创建一个内部线程变量,它将在你的循环的每一步中被检查 + QWaitCondition 来恢复它.

Ok, so I suggest you make internal thread variable that will be checked in each step of your loop + QWaitCondition to resume it.

  1. 创建暂停方法,您将在其中打开暂停字段"(布尔值?),不要忘记同步它
  2. 在您自己的循环中使用 QWaitCondition(参见 Qt 文档)暂停线程执行
  3. 创建恢复方法,您将关闭暂停字段"并唤醒 QWaitCondition

  1. Create pause method where you will switch on "pause field" (bool?), don't forget to synchronize it
  2. In your own loop use QWaitCondition (see Qt docs) to pause thread execution
  3. Create resume method where you will switch off "pause field" and wake QWaitCondition

class MyWorker: public QThread
{
private:
    QMutex sync;
    QWaitCondition pauseCond;
    bool pause;

public:
    MyWorker(...): pause(false) {}

    void resume()
    {
        sync.lock();
        pause = false;
        sync.unlock();
        pauseCond.wakeAll();
    }

    void pause()
    {
        sync.lock();
        pause = true;
        sync.unlock();
    }

protected:
    void run()
    {
        while(someCondition) // gues it's your loop
        {
             sync.lock();
             if(pause)
                 pauseCond.wait(&sync); // in this place, your thread will stop to execute until someone calls resume
             sync.unlock();

             // do your operation
        }
    }
};

这篇关于暂停和恢复 QThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆