即使使用另一个线程,启动while循环也会冻结程序

Launching a while-loop freezes program even if using another thread

本文关键字:循环 冻结 程序 while 启动 另一个 线程      更新时间:2023-10-16

在我的(Qt-)程序中,我需要一个从外部源获得的值的连续请求。但我不希望这个请求冻结整个程序,所以我为这个函数创建了一个单独的线程。但是,即使它在单独的线程中运行,GUI也会冻结。为什么?

请求功能代码:

void DPC::run()
{
    int counts = 0, old_counts = 0;
    while(1)
    {
        usleep(50000);
        counts = Read_DPC();
        if(counts != old_counts)
        {
            emit currentCount(counts);
            old_counts = counts;
        }
    }
}

Read_DPC()返回一个int值,我想将其发送到GUI中的lineEdit
主类看起来像

class DPC: public QThread
{
    Q_OBJECT
public:
    void run();
signals:
    void currentCount(int);
};

此代码在主函数中被调用为:

DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->run();

如何防止此代码冻结我的GUI?我做错了什么?谢谢

似乎您的代码是在GUI线程中运行的,因为您使用run()方法来启动线程,所以尝试调用start()作为文档和许多示例。

尝试:

DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->start();//not run

无论如何,您可以调用thread()方法或currentThread()来查看某些对象所在的线程。