c++ - Qt线程和循环问题

标签 c++ multithreading qt qthread

这是QThread子类的run方法:

void crono::Controller::run() {

    //initialise timer
    int *i = & this->model->seconds_elapsed;

    for (*i = 0; *i < this->model->seconds_total; (*i)++) {

    //calculate current seconds/minutes/hours elapsed starting  from seconds_elapsed (*i)
    this->model->tick(); 

    //should display in the form the time elapsed
    this->vista->showTime(); 
    sleep(1000);


    }

    Beep(1000, 500); //beep when all is over

}

Controller 更新模型值。

QT 窗体在启动时打开,我猜是在主应用程序线程中。

问题是鄙视 debug *i=0 和 seconds_total = X > 0,循环只执行一次,第一次 debug halt 后(没有结束),弹出窗体但没有任何反应.

我唯一能猜到的是 Controller 线程失去了它的优先级并且再也没有获得 cpu。

如何避免这种情况?

编辑 我正在尝试使用 QTimer,运气不好。

我将更新声明为公共(public)槽,然后这样实现:

void crono::Controller::update() { 

    this->modello->tick();
    this->vista->showTime();

    //eventually stop at some point (pointer to timer and timer->stop()? 
    //...
    //Beep(1000, 500);
}  

并且我在 Controller (线程)对象中插入了 QTimer 而不是循环周期:

void crono::Controller::run() {

    //inizializzo timer
    int *i = & this->modello->secondi_trascorsi;

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),this, SLOT(update()));
    timer->start(1000);


}

不知道为什么,update() 方法从来没有被调用过,而是被调用了无数次。为什么?

最佳答案

一个常见的混淆是 QThread 在它自己的独立线程中运行。不是这种情况;相反,QThread 在它控制的子线程中启动一个事件循环。 QThread 可以很容易地称为 QThreadManager

简而言之,不要继承QThread,因为您正在创建的功能位于主线程中(而不是QThread 处理的线程)。创建一个带有连接到 started() 信号的槽的 QObject 子类。然后使用 moveToThread() 并在您的 QThread 实例上调用 run()

另外,您不能直接从子线程调用主线程函数。您将需要一个排队连接信号到主线程中的对象以显示对话框。

关于c++ - Qt线程和循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14725528/

相关文章:

c++ - 何时使用信号和插槽,何时不使用

c++ - 将无符号整数与负文字进行比较

c++ - QLocale - 验证价格

python - PySide QPropertyAnimation 未启动

c++ - C++ 中的静态全局变量

c++ - QuickFIX Initiator 无法发送消息

java - 将 2 方法与另一个方法同步,但彼此之间不同步

c++ - 取消连接是 boost::asio

java - 线程 :Wait() and notify()

qt - QBluetoothSocketPrivate::__ q_readNotify()14错误